Java ArrayList Indexof示例
时间:2020-02-23 14:34:56 来源:igfitidea点击:
ArrayList的索引方法用于在ArrayList中找到第一个对象索引。
indexof方法将对象作为参数,并返回指定元素的第一个出现。
方法:
public int indexof(对象o)返回ArrayList中的第一次出现元素的索引。
indexOf method return -1 if object is not present in the ArrayList
arraylist indexof示例:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;
class IndexOfArrayListMain {
/*
* @author : igi Mandliya
*/
public static void main(String[] args) {
ArrayList employeeNameList = new ArrayList();
employeeNameList.add("John");
employeeNameList.add("Ankit");
employeeNameList.add("Rohan");
employeeNameList.add("Amit");
System.out.println("Index of Ankit: "+employeeNameList.indexOf("Ankit"));
System.out.println("***");
System.out.println("Index of John: "+employeeNameList.indexOf("John"));
System.out.println("***");
//igi is not present in the list
System.out.println("Index of igi: "+employeeNameList.indexOf("igi"));
}
}
运行上面的程序时,我们将得到以下输出
Index of Ankit: 1 *** Index of John: 0 *** Index of igi: -1

