Just like pop(), also peek() would throw an EmptyStackException if the stack is empty. What happens if we call pop() one more time? ( "stack.pop() = " + stack.pop()) Code language: Java ( java )Īs the stack is now empty, an EmptyStackException is thrown: Exception in thread "main" Īt java.base/(Stack.java:101)Īt java.base/(Stack.java:83)Īt eu.main(JavaStackDemo.java:28) Code language: plaintext ( plaintext ) Stack.pop() = apple Code language: plaintext ( plaintext ) We see that the elements are retrieved in reverse order: stack.pop() = pear ( "stack.pop() = " + stack.pop()) Code language: Java ( java ) We take out the three elements again: ( "stack.pop() = " + stack.pop()) That's because we pushed two more elements onto the stack after "apple". This means that "apple" is in the third position of the stack. The output is: arch("apple") = 3 Code language: plaintext ( plaintext ) Using search(), we can look for an element: ( "arch(\"apple\") = " + arch( "apple")) Code language: Java ( java ) The last inserted element, "pear", is at the top of the stack. So Stack's toString() method prints the elements from bottom to top. ( "stack.empty() = " + stack.empty()) Code language: Java ( java ) Stack.push( "pear") Code language: Java ( java )Īfter that, we print the stack's contents – and the results of peek() and empty() – to the console: ( "stack = " + stack) The following code snippets show an example use of Stack (you can find the complete code in the JavaStackDemo class in the GitHub repo).įirst, we create a stack and put the elements "apple", "orange", and "pear" on the stack using push(): Stack stack = new Stack() Just like Vector, Stack is thread-safe: all methods are synchronized. I show how the methods work in the following example. search() – searches for an element on the stack and returns its distance to the top of the stack.empty() – checks if the stack is empty since Stack already inherits the isEmpty() method from Vector, the empty() method is redundant why the JDK developers included it is a mystery to me.peek() – returns the top element of the stack without removing it from the stack.pop() – takes the top element from the stack.push() – places an element on the stack.Stack extends Vector with the following methods:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |