📜  Java中的 Stack indexOf(Object, int) 方法与示例

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

Java中的 Stack indexOf(Object, int) 方法与示例

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

句法:

public int indexOf(Object element, 
                        int index)

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

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

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

异常:如果指定的索引为负数,此方法将抛出IndexOutOfBoundsException

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

方案一:

// Java code to illustrate indexOf()
  
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 index:"
                           + stack.indexOf("Geeks"));
  
        // Get the second occurrence of Geeks
        // using indexOf() method
        System.out.println("The second occurrence"
                           + " of Geeks is at index: "
                           + stack.indexOf("Geeks",
                                           stack.indexOf("Geeks")));
    }
}
输出:
Stack: [Geeks, for, Geeks, 10, Geeks]
The first occurrence of Geeks is at index:0
The second occurrence of Geeks is at index: 0

程序2:演示IndexOutOfBoundsException

// Java code to illustrate indexOf()
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 -1 occurrence of Geeks
        // using indexOf() method
        System.out.println("The -1 occurrence"
                           + " of Geeks is at index: ");
  
        try {
            stack.indexOf("Geeks",
                          stack.indexOf("Geeks"));
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Stack: [1, 2, 3, 10, 20]
The -1 occurrence of Geeks is at index: 
java.lang.ArrayIndexOutOfBoundsException: -1