hacker
hacker

Reputation: 392

Confused with Object references in two different cases

Consider the following example.

    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

Now example 2(for Inserting a node at the tail of linked list):

 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;
     }    
 }

Cant understand the difference between both scenarios as both cases seems to be the same. Can someone explain...?

Upvotes: 0

Views: 63

Answers (2)

Araymer
Araymer

Reputation: 1525

So, when you say emp2=emp you've basically said "I want emp2 to point to the same memory block as emp" So, they are both pointing to the same memory. If you change that memory, they'll both fetch that same block and both reflect the change.

The second example does the same thing. However, you are updating the reference in the second one without updating the other. When you say tmp = tmp.next you update it to point to a new memory location. However, head does not get such an update. Thus, they will be different values.

So, think of it like this:

obj1 --> memory0
obj2 --> memory0

updating the values of one of these will update the values both. But...

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

Object 3 is now pointing at memory2, but object 4 is still pointing at memory 1.

Upvotes: 3

Thilo
Thilo

Reputation: 262754

The crucial difference is that in the Node example you have two Nodes, in the Employee example there is only one.

Count how many new calls there are.

Node head1=new Node();  // new instance

In the Node example, you receive one instance from outside your method, and you make another one by calling new.

Employee emp2=emp;     // additional name for existing instance

In the Employee example, you make one Employee (and then assign it to two different variables, but it's still just one object instance).

Upvotes: 0

Related Questions