java.util.AbstractSequentialList類的indexOf()方法用於返回此列表中指定元素的首次出現的索引;如果此列表不包含該元素,則返回-1。更正式地,返回最低索引i,使(o == null?get(i)== null:o.equals(get(i)));如果沒有這樣的索引,則返回-1。
用法:
public int indexOf(Object o)
參數:此方法將對象o作為要搜索的元素的參數。
返回值:此方法返回此列表中指定元素的第一個匹配項的索引;如果此列表不包含該元素,則返回-1。
異常:該方法拋出:
- ClassCastException:如果指定元素的類型與此列表不兼容。
- NullPointerException :如果指定的元素為null,並且此列表不允許使用null元素。
以下示例說明了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
相關用法
- Java AbstractSequentialList contains()用法及代碼示例
- Java AbstractSequentialList isEmpty()用法及代碼示例
- Java AbstractSequentialList lastIndexOf()用法及代碼示例
- Java AbstractSequentialList toString()用法及代碼示例
- Java AbstractSequentialList toArray()用法及代碼示例
- Java AbstractSequentialList get()用法及代碼示例
- Java AbstractSequentialList set(int, Object)用法及代碼示例
- Java AbstractSequentialList toArray(T[])用法及代碼示例
- Java AbstractSequentialList retainAll()用法及代碼示例
- Java AbstractSequentialList set()用法及代碼示例
- Java AbstractSequentialList removeAll()用法及代碼示例
- Java AbstractSequentialList.subList()用法及代碼示例
- Java AbstractSequentialList equals()用法及代碼示例
- Java AbstractSequentialList clear()用法及代碼示例
- Java AbstractSequentialList iterator()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 AbstractSequentialList indexOf() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。