Br33z3
Br33z3

Reputation: 3

Java | what is the difference between peek() and lastElement() method in Stack

Java | what is the difference between peek() and lastElement() method in Stack. They both can return the element of top of stack, is there have performance difference or something else?

Upvotes: 0

Views: 886

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79877

The only difference between these two methods is the class of the exception that gets thrown in the case where the stack is empty. Use whichever one you prefer. The standard implementations in JDK 8 are more-or-less identical, so there will be no measurable performance difference.

Possibly the reason why Stack provides a second version of the same method is that the words peek, pop and push are traditionally associated with programming a stack.

From java/util/Stack.java

 public synchronized E peek() {
    int len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);
}

and from java/util/Vector.java

 public synchronized E lastElement() {
    if (elementCount == 0) {
        throw new NoSuchElementException();
    }
    return elementData(elementCount - 1);
}

Upvotes: 1

Related Questions