Java AbstractSequentialList indexOf()方法及示例
java.util.AbstractSequentialList 类的 indexOf() 方法用于返回指定元素在这个列表中第一次出现的索引,如果这个列表不包含该元素,则返回-1。更正式的说法是,返回最低的索引i,即(o==null ? get(i)==null : o.equals(get(i))),如果没有这样的索引,则返回-1。
语法
public int indexOf(Object o)
参数: 该方法以Object o为参数,它是要搜索的元素。
返回值: 该方法返回指定元素在这个列表中第一次出现的索引,如果这个列表不包含该元素,则返回-1。
异常情况。这个方法会抛出。
- ClassCastException : 如果指定元素的类型与这个列表不兼容。
- NullPointerException : 如果指定的元素是空的,而这个列表不允许空元素。
下面是说明 indexOf() 方法的例子。
例1 :
// Java program to demonstrate indexOf()
// method for AbstractSequentialList
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating object of AbstractSequentialList
AbstractSequentialList<Integer>
arrlist1 = new LinkedList<Integer>();
// Populating arrlist1
arrlist1.add(10);
arrlist1.add(20);
arrlist1.add(30);
arrlist1.add(40);
arrlist1.add(50);
// print arrlist1
System.out.println("AbstractSequentialList: "
+ arrlist1);
// getting the index of element 30
// using indexOf() method
int index = arrlist1.indexOf(30);
// print the index
System.out.println("Index of 30: "
+ index);
}
}
输出。
AbstractSequentialList: [10, 20, 30, 40, 50]
Index of 30: 2
例2 :
// Java program to demonstrate indexOf()
// method for AbstractSequentialList
import java.util.*;
public class GFG1 {
public static void main(String[] args)
{
// Creating object of AbstractSequentialList
AbstractSequentialList<Integer>
arrlist1 = new LinkedList<Integer>();
// Populating arrlist1
arrlist1.add(10);
arrlist1.add(20);
arrlist1.add(30);
arrlist1.add(40);
arrlist1.add(50);
// print arrlist1
System.out.println("LinkedListlist: "
+ arrlist1);
// getting the index of element 100
// using indexOf() method
int index = arrlist1.indexOf(null);
// print the index
System.out.println("Index of 100: "
+ index);
}
}
输出。
LinkedListlist: [10, 20, 30, 40, 50]
Index of 100: -1
极客教程