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


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值