当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stack indexOf(Object, int)用法及代码示例


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

用法:

public int indexOf(Object element, 
                        int index)

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


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

返回值:此方法从指定的索引返回元素或元素在堆栈中首次出现的位置。否则,如果元素在堆栈中不存在,则返回-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


相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack indexOf(Object, int) method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。