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?
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.
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.
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.
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.
Since peek returns a reference to an object it would be modified.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With