11/10/2023 0 Comments Java array pop![]() What exactly does this mean? In my opinion, Stack should not be used for the following reasons: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class." The Java developers recommend not to use anymore. 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.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |