tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Stack > Stack Search

Stack Search 

The following example shows how to use Stack.search API and related operations. Stack provides the following APIs,

public int search(Object o)
 - Returns 1-based index from the top of the stack if found, other wise returns -1.  

public E push(E paramE)
 - Pushes an element onto the top of stack. 


File Name  :  
com/bethecoder/tutorials/utils/stack/StackSearch.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.stack;

import java.util.Stack;

public class StackSearch {

  /**
   @param args
   */
  public static void main(String[] args) {

    Stack<String> stack = new Stack<String>();
    stack.push("ONE");
    stack.push("TWO");
    stack.push("THREE");
    stack.push("FOUR");
    System.out.println("Stack : " + stack);
    System.out.println();
    
    for (int i = ; i < stack.size() ; i ++) {
      System.out.println("'" + stack.get(i"' found at index : " + stack.search(stack.get(i)));
    }
    
    String valToSearch = "SIX";
    System.out.println();
    System.out.println("'" + valToSearch + "' found at index : " + stack.search(valToSearch));
  }

}
   

It gives the following output,
Stack : [ONE, TWO, THREE, FOUR]

'ONE' found at index : 4
'TWO' found at index : 3
'THREE' found at index : 2
'FOUR' found at index : 1

'SIX' found at index : -1



 
  


  
bl  br