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

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

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

语法

public int indexOf(Object element, 
                        int index)

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

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

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

异常情况。如果指定的索引是负数,该方法会抛出IndexOutOfBoundsException。

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程