java indexof性能,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 stack = new Stack();

// 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 stack = new Stack();

// 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值