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


Java Stack indexOf()用法及代碼示例


Java.util.Stack.indexOf(Object element)方法用於檢查並查找Stack中特定元素的出現。如果存在該元素,則返回該元素首次出現的索引,否則,如果堆棧不包含該元素,則返回-1。

用法:

Stack.indexOf(Object element)

參數:此方法接受Stack類型的必需參數element 。它指定需要在堆棧中檢查其出現的元素。


返回值:此方法返回元素在堆棧中首次出現的索引或位置。否則,如果元素在堆棧中不存在,則返回-1。返回值是整數類型。

以下示例程序旨在說明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("20"); 
  
        // 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")); 
        System.out.println("The first occurrence"
                           + " of 10 is at index: "
                           + stack.indexOf("10")); 
    } 
}
輸出:
Stack: [Geeks, for, Geeks, 10, 20]
The first occurrence of Geeks is at index:0
The first occurrence of 10 is at index: 3

示例2:

// 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); 
  
        // The first position of an element 
        // is returned 
        System.out.println("The first occurrence"
                           + " of Geeks is at index:"
                           + stack.indexOf(2)); 
        System.out.println("The first occurrence"
                           + " of 10 is at index: "
                           + stack.indexOf(20)); 
    } 
}
輸出:
Stack: [1, 2, 3, 10, 20]
The first occurrence of Geeks is at index:1
The first occurrence of 10 is at index: 4


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack indexOf() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。