-1

I've been studying for coding interviews and I have a question about java object assignments.

say I have a Node class and I create three instances.

Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);

Now let's say I do an assignmet

a = b;

At this point I know that any change I make to the properties of Node a or b will result in a change to both a and b because this is a shallow copy.

i.e.

a.data = 99 //then b.data will become 99

or

b.data = 99 //then a.data will become 99

however if I do

b = c;

now any changes I make to the property of Node b won't have any affect on Node a.

b.data = 99;//then b.data will become 99 and c.data will become 99 but a.data will not change

I don't understand this behavior. I understand that Node b is assigned the value of Node c's address, but why doesn't this affect Node a?

intrepistar_88
  • 544
  • 1
  • 4
  • 11
  • "At this point I know that any change I make to the properties of Node a or b will result in a change to both a and b because this is a shallow copy." No, this is not correct. Your only making changes to the object itself to which each refernece points. – Kon Jan 23 '16 at 00:57
  • Welcome to StackOverflow. Please take a few minutes to visit the [help] and read [ask]. You are requested to do sufficient online research before posting to ensure your question is not trivially answered with a simple Google search (i.e. Java reference assignment). – Jim Garrison Jan 23 '16 at 01:02

1 Answers1

2

Assigning b to the object referenced by c doesn't affect a because b no longer references the same object referred to by a. Here's what is happening:

a -> (1)
b -> (2)
c -> (3)

Now a = b; is executed. Now 2 references are referring the same object. The Node containing 1 no longer has any references to it and it can be garbage collected at any time.

a -\   (1)
    \
b ---> (2)
c ---> (3)

Now b = c; is executed. This does not affect how a references its object.

a --\   (1)
     \
b -\  > (2)
    \
c ---->  (3)

Now b and c are pointing to the Node containing 3 while a continues to refer to the node containing (2). This is why a.data is not affected when b.data is changed. They are referring to different objects again.

rgettman
  • 176,041
  • 30
  • 275
  • 357