Java中地址的理解

以前不是很懂就写下了这篇文章

今天学习Python时才发现,赋值引用中出现的问题就是Java中的浅拷贝和深拷贝问题

找到一篇讲解很全面的文章

点击打开链接

---------------------------原文分隔符------------------------------------



java中没有指针,但却有地址和引用的概念。在这个地方栽了不少次。


先上一个小例子

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class Helloworld {
	static class hello{
		public int x;
	}
	 public static void main(String[] args) {
		 Queue<hello> a =new LinkedList<>();
		 hello n = new hello();
		 n.x=100;
		 a.add(n);					//添加n
		 hello c = new hello();
		 c=n;					
		 a.add(c);					//添加c
		 c.x=0;						//修改c
		 a.add(n);					//再添加n
		 System.out.println(a.size()+"\n");

		 Iterator<hello> it =a.iterator();
		 while(it.hasNext()) {
			 System.out.println(it.next().x);
		 }
	 }
}
3

0
0
0

从上面的小例子可以看出来

1.在c加入队列后,改变c的值,队列里的值也跟着改变了。

2.把n赋值给c后,更改c的值,n的值也改变了。


理解:

1.java里是有类似指针的概念的,队列其实不是真实存在,而是用链表把队列里的数据链接起来,更改原始数据实际就改变了队列里的数据。

2.java里如果把一个对象完整的赋值给另一对象,实际上他们会使用同一块地址。

上个图理解一下




如果近对对象中某一属性更改,而不是整个对象赋值,那么就不会发生引用

上代码

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class Helloworld {
	static class hello{
		public int x;
	}
	 public static void main(String[] args) {
		 Queue<hello> a =new LinkedList<>();
		 hello n = new hello();
		 n.x=100;
		 a.add(n);					//添加n
		 hello c = new hello();
		 c.x=n.x;					//仅对对象更改。
		 a.add(c);					//添加c
		 c.x=0;						//修改c
		 a.add(n);					//再添加n
		 System.out.println(a.size()+"\n");

		 Iterator<hello> it =a.iterator();
		 while(it.hasNext()) {
			 System.out.println(it.next().x);
		 }
	 }
}
3

100
0
100



版权声明:本文为Kwong_young原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。