當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。