how to search an element in a Stack using collections in java
Previous | Home | Next |
In this example we shall see how to search an element in 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 for searching an element in a Stack we have used the search(Object obj ) on the stack object. The search(Object obj) has the following syntax,
int search(Object obj)
This method returns the 1-based position where an object is in the current stack.
In this example we have created a class named CollectionExample, in which we have created a Stack to which we have added some elements by using the push(Object obj) on the object of the stack i.e stck which is done by the following statment in the code,stck.push(4);
This statement add the integer element 4 at the top of the stack.
Then we have used the search(Object obj) on the object of the stack. Then we have displayed the the search element.
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 stack
stck.push(1); // pushing element onto 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
int srchele=stck.search(3); // here we are searching which element is at index 3
System.out.println("The searched element is: "+srchele); // displaying the searched element
}
catch(EmptyStackException e)
{
e.printStackTrace();
}
}
}
The output of the above example is given as:
After pushing elements on to the stack its status is: [1, 2, 3, 4, 5, 6, 7]
The searched element is: 5
Previous | Home | Next |