Java Stack lastIndexOf()方法与实例
Java.util.Stack.lastIndexOf(Object element)方法用于检查和查找某个特定元素在堆栈中的出现。如果该元素在堆栈中存在,那么lastIndexOf()方法返回该元素最后出现的索引,否则返回-1。这个方法是用来查找一个特定元素在堆栈中的最后出现。
语法
Stack.lastIndexOf(Object element)
参数: 参数元素的类型是堆栈。它指的是需要检查其最后出现的元素。
返回值: 该方法返回该元素在Stack中最后出现的位置。如果该元素在Stack中不存在,那么该方法返回-1。返回值是整数类型的。
以下程序说明了Java.util.Stack.lastIndexOf()方法。
程序1 :
// Java code to illustrate lastIndexOf()
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 last position of an element is returned
System.out.println("Last occurrence of Geeks is at index: "
+ stack.lastIndexOf("Geeks"));
System.out.println("Last occurrence of 10 is at index: "
+ stack.lastIndexOf("10"));
}
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
Last occurrence of Geeks is at index: 2
Last occurrence of 10 is at index: 3
示例2
// Java code to illustrate lastIndexOf()
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(10);
stack.add(22);
stack.add(3);
stack.add(10);
stack.add(20);
// Displaying the Stack
System.out.println("Stack: " + stack);
// The last position of an element is returned
System.out.println("Last occurrence of 10 is at index: "
+ stack.lastIndexOf(10));
System.out.println("Last occurrence of 20 is at index: "
+ stack.lastIndexOf(20));
}
}
输出:
Stack: [10, 22, 3, 10, 20]
Last occurrence of 10 is at index: 3
Last occurrence of 20 is at index: 4
极客教程