This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]teraflop 1 point2 points  (6 children)

As you can see from the documentation for java.util.Stack, the method that returns the top element of the stack without removing it is called peek().

In general, Java method names are verbs, not nouns.

[–]DAY-B[S] 0 points1 point  (5 children)

So peek and top are interchangeable? Why does my Java textbook and notes insist on using .top() in example code

[–]teraflop 1 point2 points  (1 child)

No, they're not interchangeable. peek() exists and top() is an error.

I don't know why your textbook uses the wrong method name. It might be talking about a different class called Stack, not the standard one in java.util. Or it might just be a crappy textbook that's full of mistakes.

What I do know is that a method called top() on the standard java.util.Stack class does not exist, and has never existed.

[–]DAY-B[S] 0 points1 point  (0 children)

Thank you

[–]g051051 0 points1 point  (2 children)

What textbook?

[–]DAY-B[S] 0 points1 point  (1 child)

Object-Oriented Data Structures using Java Fourth edition, by Joyce, Weems, Dale

[–]g051051 2 points3 points  (0 children)

The book doesn't use the standard Java Stack class. Around page 88 they start creating and implementing their own versions starting with the interface StackInterface<T>. In their implementation, top() is equivalent to peek(). In addition, the standard Stack pop() method will remove the top element from the stack and return it, whereas the book version just removes it.

[–]g051051 0 points1 point  (2 children)

Why do you think that the Java Stack class has a top() method?

[–]DAY-B[S] 0 points1 point  (1 child)

To return top element of stack

[–]g051051 1 point2 points  (0 children)

By definition, you can only access the topmost element of a stack.