how to create a stack using collections in java
Previous | Home | Next |
In this example we will create a stack.
In this example we will create a stack. For creating a stack we have import the java.util package which contains the java.util.Stack class. In the following example we have created a class named CollectionExample in which we have created a Stack object and added some elements to it.
In this example we have created a Stack object by using the following statement,
Stack<Integer>stck=new Stack<Integer>();
This statement will creates an empty stack named stckFor adding the elements to the stack we have used the push() method on the object of the Stack. The following statement shows how to do this,
stck.push(1);
This statement adds the integer value 1 at the top of the stack.The general syntax of the push() method is given as,
push(Object obj)
This method pushes an item onto the top of the current stack.
For removing the elements from this stack we used the following method,
pop()
This method removes the object at the top of the stack and returns that object as the value of this function.
In this example we have created a class named CollectionExample in which we have created a stack by using the following statment
Stack<Integer>stck=new Stack<Integer>();
The items to this stack are added by using the push(Object obj) on the object of the stack i.e stck(in this example) which is done as,
stck.push(1);
This statement adds the integer value 1 at the top of the stack. For deleting the element from this stack we have used the pop() method on its object which is shown by this statement in the example,stck.pop();Finally we have displayed the contents of the Stack.
package r4r.co.in;
import java.util.*;
public class CollectionExample
{
/**
* @param args
*/
public static void main(String args[]) throws EmptyStackException
{
try
{
Stack<Integer> stck=new Stack<Integer>(); // creating a new empty stack
stck.push(1); // pushing elements on to the stack
stck.push(2);
stck.push(3);
stck.push(4);
stck.push(5);
stck.push(6);
stck.push(7);
System.out.println("After pushing elements on to the stack its status is: "+stck); // displaying the contents of the stack
stck.pop(); // removing or popping out the topmost element of the stack
stck.pop();
stck.pop();
System.out.println("After poping up the elements, the status of stack is: "+stck); // showing the contents of the stack after deletion
}
catch(EmptyStackException e) // handling the EmptyStackException which is thrown during the poping of stack elements
{
e.printStackTrace();
}
}
}
The output of the above example is as follows:
After pushing elements on to the stack its status is: [1, 2, 3, 4, 5, 6, 7]
After poping up the elements, the status of stack is: [1, 2, 3, 4]
Previous | Home | Next |