ArrayList的indexOf()方法返回此列表中指定元素的第一個匹配項的索引;如果此列表不包含該元素,則返回-1。
用法:
public int IndexOf(Object o) obj : The element to search for.
// Java code to demonstrate the working of
// indexOf in ArrayList
// for ArrayList functions
import java.util.ArrayList;
public class IndexOfEx {
public static void main(String[] args) {
// creating an Empty Integer ArrayList
ArrayList<Integer> arr = new ArrayList<Integer>(5);
// using add() to initialize values
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
// printing initial value
System.out.print("The initial values in ArrayList are : ");
for (Integer value : arr) {
System.out.print(value);
System.out.print(" ");
}
// using indexOf() to find index of 3
int pos =arr.indexOf(3);
// prints 2
System.out.println("\nThe element 3 is at index : " + pos);
}
}
輸出:
The initial values in ArrayList are : 1 2 3 4 The element 3 is at index : 2
實際應用:索引函數在確定事件的最後出現或首次出現時非常有用,例如在擲骰子中最後出現6次或在名稱中第一次出現任何字母等。
再舉一個例子:
// Java code to demonstrate the application of
// index functions in ArrayList
// for ArrayList functions
import java.util.ArrayList;
public class AppliIndex {
public static void main(String[] args) {
// creating an Empty Integer ArrayList
ArrayList<Integer> arr = new ArrayList<Integer>(10);
// using add() to initialize dice values
arr.add(1);
arr.add(2);
arr.add(4);
arr.add(6);
arr.add(5);
arr.add(2);
arr.add(6);
arr.add(1);
arr.add(6);
arr.add(4);
// using IndexOf() to find first index of 6
int pos1 =arr.indexOf(6);
// using lastIndexOf() to find last index of 6
int pos2 =arr.lastIndexOf(6);
// to balance 0 based indexing
pos1 = pos1+1;
pos2 = pos2+1;
// printing first index of 6
System.out.println("The first occurrence of 6 is : " + pos1);
// printing last index of 6
System.out.println("The last occurrence of 6 is : " + pos2);
}
}
輸出:
The first occurrence of 6 is : 4 The last occurrence of 6 is : 9
相關用法
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java.util.concurrent.Phaser用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java.util.concurrent.RecursiveTask用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java lang.Long.builtcount()用法及代碼示例
- Java Java lang.Long.reverse()用法及代碼示例
- Java Java.util.function.IntPredicate用法及代碼示例
注:本文由純淨天空篩選整理自 Java.util.Arraylist.indexOf() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。