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

标签 java object reference linked-list

考虑以下示例。

    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/

相关文章:

java - 使用 JAXB 解码具有相同名称的 XML 标签

javascript - Firestore 更新数组字段中的单个项目

javascript - 如何在Javascript中创建数组之间的主/从关系?

c# - 命名空间 'Reporting' 中不存在类型或命名空间名称 'Microsoft'

java - 有没有办法以编程方式暂停 Tomcat 监听 http 端口

java - 将 PHP hash_file 与 Java 输出进行比较

java - java中如何仅从服务器获取网页的头部

c++ - 在 QMainWindow 中显示 QGridLayout

java - POJO 是反面向对象(OO)的吗?

php - JavaScript 通过引用传递变量