Stack is a LIFO ADT (Last in first out abstract data type) and a linear data structure. In a jar the items on top (i.e. items that went in last) come our first. In a LIFO ADT, items that go in last come our first.
Stacks are a very useful data structure. Although you have the possibility of creating your own stack data structure from Java code, it is a better idea to simply use the stack provided by Java.
Code Following code shows how to use Java’s stack:
import java.util.*;
public class UseStack{
public static void main(String[] args) {
Stack st = new Stack();
st.push(new Integer(100));
st.push("kcats");
System.out.println("Stack contents: " + st);
System.out.println(st.pop());
st.pop();
if (st.empty()) {
st.push("stack");
}
System.out.println("Stack size: " + st.size());
System.out.println(st.peek());
System.out.println("Stack size: " + st.size());
}
}
Output
Stack contents: [100, kcats]
kcats
Stack size: 1
stack
Stack size: 1
Explanation Stack is created by instantiating the Stack class. It accepts any object. Here I have added Integer and String. When you call System.out.print() on the stack object, its contents are printed in string format.
- push() adds an item
- pop() removes the top item
- peek() simply shows the first item without removing it
- empty() returns true if the stack is empty
- size() returns the size of the stack i.e. how many items does it contain