Java Stack indexOf()方法与实例
Java.util.Stack.indexOf(Object element)方法用于检查和查找某个特定元素在堆栈中的出现。如果该元素存在,则返回该元素第一次出现的索引,否则,如果堆栈中不包含该元素,则返回-1。
语法
Stack.indexOf(Object element)
参数: 该方法接受一个Stack类型的强制性参数element。它指定了需要在Stack中检查其出现的元素。
返回值: 该方法返回该元素在堆栈中第一次出现的索引或位置。否则,如果该元素在Stack中不存在,则返回-1。返回的值是整数类型的。
以下程序说明了Java.util.Stack.indexOf()方法。
程序1 :
// Java code to illustrate indexOf()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Displaying the Stack
System.out.println("Stack: " + stack);
// The first position of an element
// is returned
System.out.println("The first occurrence"
+ " of Geeks is at index:"
+ stack.indexOf("Geeks"));
System.out.println("The first occurrence"
+ " of 10 is at index: "
+ stack.indexOf("10"));
}
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
The first occurrence of Geeks is at index:0
The first occurrence of 10 is at index: 3
示例2
// Java code to illustrate indexOf()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack = new Stack<Integer>();
// Use add() method to add elements in the Stack
stack.add(1);
stack.add(2);
stack.add(3);
stack.add(10);
stack.add(20);
// Displaying the Stack
System.out.println("Stack: " + stack);
// The first position of an element
// is returned
System.out.println("The first occurrence"
+ " of Geeks is at index:"
+ stack.indexOf(2));
System.out.println("The first occurrence"
+ " of 10 is at index: "
+ stack.indexOf(20));
}
}
输出:
Stack: [1, 2, 3, 10, 20]
The first occurrence of Geeks is at index:1
The first occurrence of 10 is at index: 4
极客教程