Java 如何在List中找到元素
Java List提供了一个方法indexOf(),可以用来获取列表中元素的位置。
int indexOf(Object o)
返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回-1。更正式地说,返回最低索引i,使得(o==null ? get(i)==null : o.equals(get(i)))
,如果不存在这样的索引则返回-1。
参数
- o - 要搜索的元素。
返回
返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回-1。
异常
- ClassCastException - 如果指定元素的类型与此列表不兼容(可选)。
-
NullPointerException - 如果指定元素为null并且此列表不允许null元素(可选)。
示例
以下示例显示了indexOf()方法的用法:
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(1, "Zara"));
list.add(new Student(2, "Mahnaz"));
list.add(new Student(3, "Ayan"));
System.out.println("List: " + list);
Student student = new Student(3, "Ayan");
Student missingStudent = new Student(4, "Aman");
System.out.println("Ayan is present at: " + list.indexOf(student));
System.out.println("Aman index: " + list.indexOf(missingStudent));
}
}
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student)) {
return false;
}
Student student = (Student)obj;
return this.id == student.getId() && this.name.equals(student.getName());
}
@Override
public String toString() {
return "[" + this.id + "," + this.name + "]";
}
}
输出
这将产生以下结果-
List: [[1,Zara], [2,Mahnaz], [3,Ayan]]
Ayan is present at: 2
Aman index: -1