In this guide, you will learn about the Stack search() method in Java programming and how to use it with an example.
1. Java Stack search() Method Overview
Definition:
The search() method of the Java Stack class searches for an element in the stack and determines how far the element is from the top of the stack.
Syntax:
stack.search(Object o);
Parameters:
- Object o: The element to be searched in the stack.
Key Points:
- The method returns the 1-based position from the top of the stack where the object is located.
- If the object is not found, the method returns -1.
- The search considers the topmost occurrence if there are multiple occurrences of the object in the stack.
2. Java Stack search() Method Example
import java.util.Stack;
public class StackSearchExample {
public static void main(String[] args) {
Stack<String> names = new Stack<>();
// Adding elements to the stack for demonstration
names.push("Alice");
names.push("Bob");
names.push("Charlie");
names.push("Bob");
System.out.println("Stack: " + names);
// Searching for an element present in the stack
System.out.println("Position of 'Bob' from the top: " + names.search("Bob"));
// Searching for an element not present in the stack
System.out.println("Position of 'Eve' from the top: " + names.search("Eve"));
}
}
Output:
Stack: [Alice, Bob, Charlie, Bob] Position of 'Bob' from the top: 1 Position of 'Eve' from the top: -1
Explanation:
In the example, we have a Stack (named 'names') with a few names.
When we search for "Bob", the method returns 1, indicating that "Bob" is at the topmost position. If an element is not present in the stack, like "Ramesh", the search() method returns -1, indicating the absence of the element.
It's important to note that the search considers the topmost occurrence, so even though "Bob" is present twice, the position returned is 1 since the topmost occurrence of "Bob" is at the top.
Related Stack and Queue Class methods
Java Queue offer() exampleJava Queue poll() example
Java Queue peek() example
Java Stack push() example
Java Stack pop() example
Java Stack peek() example
Java Stack search() example
Comments
Post a Comment
Leave Comment