How do I use the Stack class in Java?
Category: java.util, viewed: 820 time(s).
Stack is an extension of the java.util.Vector class that provided a LIFO (last-in-first-out) data structure. This class provide the usual method such as push and pop. The peek method is used the get the top element of the stack without removing the item.
package org.kodejava.example.lang; import java.util.Stack; public class StackExample { public static void main(String[] args) { Stack stack = new Stack(); // // We stored some values in the stack object. // for (int i = 0; i < 10; i++) { stack.push(i); System.out.print(i + " "); } System.out.println(""); // // Searching for an item in the stack. The position returned as the // distance from the top of the stack. Here we search for the 3 number // in the stack which is in the 7th row of the stack. // int position = stack.search(3); System.out.println("Search result position: " + position); // // The current top value of the stack // System.out.println("Stack top: " + stack.peek()); // // Here we popping out all the stack object items. // while (!stack.empty()) { System.out.print(stack.pop() + " "); } } } |
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I sort items of an ArrayList?
- How do I sort array values in case insensitive order?
- How do I sort array values in descending order?
- How do I convert milliseconds value to date?
- How do I split a string using Scanner class?
- How do I read file using Scanner class?
- How do I read / write data in Windows registry?
- How do I read user input from console using Scanner class?
- How do I use ResourceBundle for i18n?
- How do I convert time between timezone?