gpt4 book ai didi

java - 在两种不同情况下与对象引用混淆

转载 作者:行者123 更新时间:2023-12-01 21:49:28 24 4
gpt4 key购买 nike

考虑以下示例。

    Employee emp = new Employee();

emp.name="John";
emp.id=3;

Employee emp2=emp;

System.out.println(emp.toString()); // prints 3 John
System.out.println(emp2.toString()); // prints 3 john

emp2.name="Cena";
emp2.id=9;

System.out.println(emp.toString()); //prints 9 Cena
System.out.println(emp2.toString()); //prints 9 Cena here whatever changes made to emp2 are refletced in emp object too

现在示例2(在链表尾部插入节点):

 static Node Insert(Node head,int data) {   
Node head1=new Node(); // New node for insertion
head1.data=data;
head1.next=null;

if(head==null) {
head=head1;
return head;
}
else {
Node tmp=head; // here both tmp and head needs to be same always as in the previous exaample
while(tmp.next!=null) {
tmp=tmp.next;// but head and tmp are not equal after an iteration why...?
}
tmp.next=head1;
return head;
}
}

无法理解这两种情况之间的区别,因为这两种情况似乎是相同的。有人可以解释一下吗...?

最佳答案

所以,当你说emp2=emp时,你基本上是在说“我希望emp2指向与emp相同的内存块”,所以,它们都指向相同的内存。如果您更改该内存,它们都会获取相同的 block 并反射(reflect)更改。

第二个例子做了同样的事情。但是,您正在更新第二个引用中的引用,而不更新另一个引用。当您说tmp = tmp.next时,您会更新它以指向新的内存位置。然而,head 没有得到这样的更新。因此,它们将是不同的值。

所以,可以这样想:

obj1 --> memory0
obj2 --> memory0

更新其中一个的将会更新两者的。但是...

obj3 --> memory1
obj4 --> memory1
obj3 --> memory.next (memory2)

对象 3 现在指向内存 2,但对象 4 仍然指向内存 1。

关于java - 在两种不同情况下与对象引用混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35401309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com