Stack implementation and shallow copy
Im new the the shallow copy/deep copy concept. I need a little help understanding whats actually going on in this implementation:
Code :
public class Stack1 {
private Object value;
private Stack1 rest;
private boolean empty;
public boolean isEmpty() { return empty; }
public Stack1() {
value = null;
rest = null;
empty = true;
}
private Stack1(Stack1 other){ //Make fields of this object point to the same objects in another stack's fields i.e. shallow copy
this.value = other.value;
this.rest = other.rest;
this.empty = other.empty;
}
public void push(Object x){
this.rest = new Stack1(this); //What's going on here?
this.value = x;
this.empty = false;
}
In the push method we make a shallow copy on the RHS which means that there is some object whose fields are referencing the same memory blocks as our current stack object (this). But we then go ahead and say, ok now take our current object (this) and set its rest to be this copy. But this.rest has just been altered, doesn't that mean the object copy's rest will be referencing itself? so its like some kind of infinite loop now???
HELP!
Thanks
Re: Stack implementation and shallow copy
Am I thinking about this wrong?... is it only if I alter the object its referencing (using mutator methods) rather than the variable holding the reference? I think this might be my issue.. so if I did something like
this.rest.pop()
then a clone would also have its rest popped?
but if i went this.rest = new Object()
then the clones rest would still be the old this.rest?
Re: Stack implementation and shallow copy
It looks perfectly fine to me.
A good way to treat variables in Java is as a pointer or address.
Code java:
this.rest = new Stack1(this);
Before executing this line, this.rest points to something (could be an object or null, doesn't matter). An analogy would be if you had an address to a house on a piece of paper (say your friend Bob's house).
In the constructor of the new Stack1 object, it's copying that address but not the object. This could be viewed as your friend Gary copying the address you have written down for Bob. Now if you both go to the same address, you'll find the same house and if you decide to paint the walls yellow, you're friend will see that Bob has yellow walls.
However, back in the push method, you modify your this.rest. This is analogous to you changing the address you have written down to the address of Gary's house. It has no effect on the address your friend Gary has written down, which still points to Bob's house. Now if you go and modify Gary's house, the changes won't be visible at Bob's house.
It is interesting to note, that by going to Gary's house you can still find Bob's house. Since Gary has Bob's address written down and you know where Gary lives, you just go to Gary's house and ask him. The java code would be this.rest.rest (assuming you're at the end of the push method).