Java Stack lastIndexOf(Object, int)方法与实例

Java Stack lastIndexOf(Object, int)方法与实例

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

语法

public int lastIndexOf(Object element, 
                        int last_index)

参数: 该方法接受两个参数。

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

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

异常情况。如果指定的索引大于或等于这个向量的当前大小,这个方法会抛出IndexOutOfBoundsException。

以下程序说明了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("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<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);
  
        // 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程