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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。