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?
Then you would have to create new instance of
Animal.When you add the
Animalreference in theStack, you are just storing a copy of the reference, which points to the sameAnimal. So, if you modify yourAnimalinstance using original reference, it is also modified for the reference in theStack.So, you need to modify your code like this: –