Java 如何检查ArrayList是否包含某个元素
您可以利用List接口的contains()方法来检查列表中是否存在一个对象。
contains()方法
boolean contains(Object o)
如果此列表包含指定的元素,则返回true。更正式地说,当且仅当此列表包含至少一个元素e满足(o==null ? e==null : o.equals(e))
时,返回true。
参数
- c - 要测试其存在于此列表中的元素。
返回值
如果此列表包含指定的元素,则返回true。
抛出异常
- ClassCastException - 如果指定元素的类型与此列表不兼容(可选)。
- NullPointerException - 如果指定的元素为空且此列表不允许空元素(可选)。
示例
以下示例展示了contains()方法的用法:
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List 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");
if(list.contains(student)) {
System.out.println("Ayan is present.");
}
}
}
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 + "]";
}
}
输出
这将产生以下结果 –
Note: com/tutorialspoint/CollectionsDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
List: [[1,Zara], [2,Mahnaz], [3,Ayan]]
Ayan is present.