📜  在Java中使用示例堆栈 lastIndexOf(Object, int) 方法

📅  最后修改于: 2022-05-13 01:55:21.190000             🧑  作者: Mango

在Java中使用示例堆栈 lastIndexOf(Object, int) 方法

Java.util.Stack.lastIndexOf(Object element, int last_index)方法用于此Stack中指定元素第一次出现的最后一个索引,从最后一个索引开始向前搜索,如果没有找到则返回-1 .更正式地说,返回最低的最后一个索引 i 使得 (i >= last index && Objects.equals(o, get(i))),如果没有这样的最后一个索引,则返回 -1。

句法:

public int lastIndexOf(Object element, 
                        int last_index)

参数:此方法接受两个参数:

  • Stack 类型的元素。它指定需要在堆栈中检查其出现的元素。
  • Integer 类型的最后一个索引。它指定开始搜索的最后一个索引

返回值:此方法从指定的最后一个索引返回堆栈中第一次出现的元素的最后一个索引或位置。否则,如果堆栈中不存在该元素,则返回-1 。返回值是整数类型。

异常:如果指定的索引大于或等于此向量的当前大小,则此方法抛出IndexOutOfBoundsException

下面的程序说明了Java.util.Stack.lastIndexOf() 方法:

方案一:

// Java code to illustrate lastIndexOf()
  
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // Use add() method to add elements in the Stack
        stack.add("Geeks");
        stack.add("for");
        stack.add("Geeks");
        stack.add("10");
        stack.add("Geeks");
  
        // 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 last index:"
                           + stack.indexOf("Geeks"));
  
        // Get the last occurrence of Geeks
        // using lastIndexOf() method
        System.out.println("The last occurrence"
                           + " of Geeks is at last index: "
                           + stack
                                 .lastIndexOf("Geeks",
                                              stack.lastIndexOf("Geeks")));
    }
}
输出:
Stack: [Geeks, for, Geeks, 10, Geeks]
The first occurrence of Geeks is at last index:0
The last occurrence of Geeks is at last index: 4

程序2:演示IndexOutOfBoundsException

// Java code to illustrate lastIndexOf()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // 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);
  
        // Get the 10th occurrence of Geeks
        // using lastIndexOf() method
        System.out.println("The 10th occurrence"
                           + " of Geeks is at index: ");
  
        try {
            stack.lastIndexOf("Geeks", 10);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Stack: [1, 2, 3, 10, 20]
The 10th occurrence of Geeks is at index: 
java.lang.IndexOutOfBoundsException: 10 >= 5