java indexof int_Java Stack indexOf(Object, int)用法及代码示例
Java.util.Stack.indexOf(Object element,int index)方法用于在此Stack中首次出現指定元素的索引,從索引開始向前搜索,如果找不到該元素,則返回-1。更正式地,返回最低索引i,使(i> = index && Objects.equals(o,get(i))),如果沒有這樣的索引,則返回-1。
用法:
public int indexOf(Object element,
int index)
參數:此方法接受兩個參數:
element類型的堆棧。它指定需要在堆棧中檢查其出現的元素。
index類型為Integer。它指定要從中開始搜索的索引
返回值:此方法從指定的索引返回元素或元素在堆棧中首次出現的位置。否則,如果元素在堆棧中不存在,則返回-1。返回值是整數類型。
異常:如果指定的索引為負,則此方法將引發IndexOutOfBoundsException。
以下示例程序旨在說明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("Geeks");
// 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"));
// Get the second occurrence of Geeks
// using indexOf() method
System.out.println("The second occurrence"
+ " of Geeks is at index:"
+ stack.indexOf("Geeks",
stack.indexOf("Geeks")));
}
}
輸出:
Stack:[Geeks, for, Geeks, 10, Geeks]
The first occurrence of Geeks is at index:0
The second occurrence of Geeks is at index:0
程序2:演示IndexOutOfBoundsException
// 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);
// Get the -1 occurrence of Geeks
// using indexOf() method
System.out.println("The -1 occurrence"
+ " of Geeks is at index:");
try {
stack.indexOf("Geeks",
stack.indexOf("Geeks"));
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
Stack:[1, 2, 3, 10, 20]
The -1 occurrence of Geeks is at index:
java.lang.ArrayIndexOutOfBoundsException:-1
總結
以上是生活随笔為你收集整理的java indexof int_Java Stack indexOf(Object, int)用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java判断星期天_java实现一个月的
- 下一篇: 南邮java大作业实验报告_南京邮电大学