1
Stack<Animal> myStack = new Stack<Animal>();
Animal a = new Animal();
a.setValueOfAnimal(5);
myStack.push(a);
a.setValueOfAnimal(15);
System.out.println(myStack.pop().getValueOfAnimal());

Above you see a sample main method.

The output will be : 15.

Is there anyway to make the object in the stack safe? I do not want the object in the stack to be modified when I modify the value of "Animal a".

Is this supported by any built - in Java class?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • Any object you want the stack to make a copy of must first *be copyable*, e.g., by implementing the [`Clonable`](http://docs.oracle.com/javase/6/docs/api/java/lang/Cloneable.html) interface, which requires that it implement [`.clone()`](http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29). No data structure can make a copy of an object if it's not clear *how* a copy should be made. – apsillers Nov 29 '12 at 19:43

4 Answers4

6

I do not want the object in the stack to be modified when I modify the value of "Animal a".

Then you would have to create new instance of Animal.

When you add the Animal reference in the Stack, you are just storing a copy of the reference, which points to the same Animal. So, if you modify your Animal instance using original reference, it is also modified for the reference in the Stack.

So, you need to modify your code like this: -

myStack.push(a);
a = new Animal(); // Make the reference `a` point to a new instance.
a.setValueOfAnimal(15);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

You can't, unless you add a = new Animal() after myStack.push(a);.

What you could also do is provide a copy constructor:

public Animal(Animal someAnimal) {
    this.value = someAnimal.value;
}

You could then write:

myStack.push(new Animal(a)); //put a copy in the stack
assylias
  • 321,522
  • 82
  • 660
  • 783
2

Nulling references after pushing would make objects on stack safe:

Animal a = new Animal();
a.setValueOfAnimal(5);
myStack.push(a);
a = null;  // remark here.
Juvanis
  • 25,802
  • 5
  • 69
  • 87
0

Your code visual flow will be as the below diagram:

enter image description here

Hint:
Java parameters passing is “pass-by-value”, the value will be the reference address in case of an object value.

Why the unexpected issue:
You update the method parameter Animal a data after calling myStack.push(a); method.

If you don't' need this behavior:

  • Either nullify the reference pointer after calling myStack.push(a); method.
    a = null;
  • Or you use can use the same reference name a to create a new object in memory
    a = new Animal();
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88