Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading