Stack search(Object) in Java

search(Object): This method is available in java.util.Stack class of Java.

Syntax:

int java.util.Stack.search(Object o)

This method takes one argument. This method returns the 1-based position where an object is on this stack.

Note: If the object o occurs as an item in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack.

Parameters: One parameter is required for this method.

o: the desired object.

Returns: the 1-based position from the top of the stack where the object is located; the return value -1indicates that the object is not on the stack.

Exceptions: NA

Approach

Java

import java.util.Stack;

public class Stacksearch {
    public static void main(String[] args) {

        Stack<Integer> st = new Stack<>();

        st.push(1);
        st.push(18);
        st.push(29);
        st.push(8);

        System.out.println(st.search(1));

    }
}

Output:

4


No comments:

Post a Comment