Java中的java.util.Stack.search(Object element)方法用於搜索堆棧中的元素並獲取其與頂部的距離。此方法從1開始而不是從0開始計數位置。位於堆棧頂部的元素被視為在位置1。如果存在多個元素,則最接近頂部的元素的索引返回。如果成功找到該元素,則該方法返回其位置;如果缺少該元素,則返回-1。
用法:
STACK.search(element)
參數:該方法接受一個參數element ,該參數element 引用需要在堆棧中搜索的元素。
返回值:如果在堆棧中成功找到該元素,則該方法將返回該元素的位置(以計數為基數1),否則返回-1。
以下程序說明了java.util.Stack.search()方法的用法:
示例1:
// Java code to demonstrate search() method
import java.util.*;
public class Stack_Demo {
public static void main(String[] args)
{
// Creating an empty Stack
Stack<String> STACK = new Stack<String>();
// Stacking strings
STACK.push("Geeks");
STACK.push("4");
STACK.push("Geeks");
STACK.push("Welcomes");
STACK.push("You");
// Displaying the Stack
System.out.println("The stack is: " + STACK);
// Checking for the element "4"
System.out.println("Does the stack contains '4'? "
+ STACK.search("4"));
// Checking for the element "Hello"
System.out.println("Does the stack contains 'Hello'? "
+ STACK.search("Hello"));
// Checking for the element "Geeks"
System.out.println("Does the stack contains 'Geeks'? "
+ STACK.search("Geeks"));
}
}
輸出:
The stack is: [Geeks, 4, Geeks, Welcomes, You] Does the stack contains '4'? 4 Does the stack contains 'Hello'? -1 Does the stack contains 'Geeks'? 3
示例2:
// Java code to demonstrate search() method
import java.util.*;
public class Stack_Demo {
public static void main(String[] args)
{
// Creating an empty Stack
Stack<Integer> STACK = new Stack<Integer>();
// Stacking int values
STACK.push(8);
STACK.push(5);
STACK.push(9);
STACK.push(2);
STACK.push(4);
// Displaying the Stack
System.out.println("The stack is: " + STACK);
// Checking for the element 9
System.out.println("Does the stack contains '9'? "
+ STACK.search(9));
// Checking for the element 10
System.out.println("Does the stack contains '10'? "
+ STACK.search(10));
// Checking for the element 11
System.out.println("Does the stack contains '11'? "
+ STACK.search(11));
}
}
輸出:
The stack is: [8, 5, 9, 2, 4] Does the stack contains '9'? 3 Does the stack contains '10'? -1 Does the stack contains '11'? -1
相關用法
- Java Stack get()用法及代碼示例
- Java Stack pop()用法及代碼示例
- Java Stack contains()用法及代碼示例
- Java Stack set()用法及代碼示例
- Java Stack indexOf()用法及代碼示例
- Java Stack lastElement()用法及代碼示例
- Java Stack containsAll()用法及代碼示例
- Java Stack setElementAt()用法及代碼示例
- Java Stack insertElementAt()用法及代碼示例
- Java Stack add(Object)用法及代碼示例
- Java Stack copyInto()用法及代碼示例
- Java Stack clear()用法及代碼示例
- Java Stack add(int, Object)用法及代碼示例
- Java Stack equals()用法及代碼示例
- Java Stack setSize()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Stack search() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。