Java stack hint

Hi everyone, there was something interesting about Java Stacks. Does peek () call a link to the actual object at the top of the stack or a copy of the object? For example, if I run the following code:

Stack.peek().setName("name"); 

Can this change the name field of the object located at the top of the stack, or a completely different object with the same values ​​for all its fields?

+6
source share
4 answers

Since peek returns a reference to the object, it will be modified.

+7
source

In general, very few bits of code in Java go around arbitrary copying of objects. peek will return the link that is on the top of the stack ... do not forget that objects are not on the stack, in the first place, only links.

So, in your example, you really change the name of the object referenced by the link in the stack.

+8
source

Definitely a link. He will change the name.

+2
source

In http://download.oracle.com/javase/6/docs/api/java/util/Stack.html I don't see evidence why it will return a copy, so I really think this will change the original

+1
source

Source: https://habr.com/ru/post/886379/


All Articles