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


Java Stack lastIndexOf()用法及代码示例


Java.util.Stack.lastIndexOf(Object element)方法用于检查并查找Stack中特定元素的出现。如果元素存在于堆栈中,则lastIndexOf()方法将返回该元素最后一次出现的索引,否则将返回-1。此方法用于查找堆栈中特定元素的最后一次出现。

用法:

Stack.lastIndexOf(Object element)

参数:参数element 的类型为Stack。它指的是需要检查其最后一次出现的元素。


返回值:该方法返回元素在堆栈中最后一次出现的位置。如果元素不在堆栈中,则该方法返回-1。返回值是整数类型。

以下示例程序旨在说明Java.util.Stack.lastIndexOf()方法:

示例1:

// Java code to illustrate lastIndexOf() 
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 last position of an element is returned 
        System.out.println("Last occurrence of Geeks is at index: "
                           + stack.lastIndexOf("Geeks")); 
        System.out.println("Last occurrence of 10 is at index: "
                           + stack.lastIndexOf("10")); 
    } 
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
Last occurrence of Geeks is at index: 2
Last occurrence of 10 is at index: 3

示例2:

// Java code to illustrate lastIndexOf() 
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(10); 
        stack.add(22); 
        stack.add(3); 
        stack.add(10); 
        stack.add(20); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // The last position of an element is returned 
        System.out.println("Last occurrence of 10 is at index: "
                           + stack.lastIndexOf(10)); 
        System.out.println("Last occurrence of 20 is at index: "
                           + stack.lastIndexOf(20)); 
    } 
}
输出:
Stack: [10, 22, 3, 10, 20]
Last occurrence of 10 is at index: 3
Last occurrence of 20 is at index: 4


相关用法


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