Java.util.Stack 类

java.util.Stack.indexOf() 方法返回此堆栈中指定元素第一次出现的索引,从指定索引向前搜索。如果堆栈中不存在元素,则返回 -1。

语法

public int indexOf(Object o, int index)

参数

o 指定要在堆栈中搜索的元素。
index 指定索引到search 搜索自。

返回值

返回指定元素在堆栈中第一次出现的索引,向前搜索指定索引,如果元素不存在于堆栈中,则为 -1。

异常

不适用。

示例:

在下面的示例中,java.util.Stack.indexOf()方法用于查找堆栈MyStack中指定元素第一次出现的索引,从指定索引处向前搜索。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建堆栈
    Stack<Integer> MyStack = new Stack<Integer>();

    //填充堆栈
    MyStack.push(10);
    MyStack.push(30);
    MyStack.push(20);
    MyStack.push(50);
    MyStack.push(30);

    System.out.print("30 appeared first time after index=2 at index="); 
    System.out.print(MyStack.indexOf(30, 2));
  }
}

上述代码的输出将是:

30 appeared first time after index=2 at index=4