Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stack peek

Hey all, was wondering something about Java Stacks. Does peek() return a reference to the actual object on the top of the stack or a copy of the object? For instance, if I ran the following code:

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

Would this modify the name field of the object currently at the top of the stack, or to a completely different object with identical values for all it's fields?

like image 659
Richard Stokes Avatar asked Apr 21 '11 10:04

Richard Stokes


People also ask

What is peek in stack in Java?

Stack peek() Method in Java The java. util. Stack. peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack.

Is peek a stack operation?

In computer science, peek is an operation on certain abstract data types, specifically sequential collections such as stacks and queues, which returns the value of the top ("front") of the collection without removing the element from the collection.

Is peek same as top in stack?

peek() & top() functions are same but peek() is unavailable in std::stack . You can check it here- http://www.cplusplus.com/reference/stack/stack/ . Actually, peek() and top() both take O(1) time without any other queries.

What is the difference between the stack peek and pop operations?

A stack implementation typically contains three methods, which as push, pop, and peek. Push will allow the user to put a single item onto the stack. Peek allows the user to see what value is on top of the stack, and pop allows the user to remove the top value from the stack.


2 Answers

Since peek returns a reference to an object it would be modified.

like image 120
stacker Avatar answered Oct 12 '22 01:10

stacker


In general, very few bits of code in Java go round arbitrarily creating copies of objects. peek will return the reference that's on the top of the stack... don't forget that the objects aren't on the stack in the first place, only the references.

So in your example, you would indeed modify the name of the object that the reference on the stack refers to.

like image 36
Jon Skeet Avatar answered Oct 12 '22 00:10

Jon Skeet