如何检查 Java 中的 ArrayList 是否包含一项?
你可以使用 List 接口的 contains() 方法来检查列表中是否存在某个对象。
contains() 方法
boolean contains(Object o)
如果此列表包含指定元素,则返回真。更正式地说,当且仅当此列表包含至少一个元素 e,使得 (o==null ? e==null : o.equals(e)) 为真时,返回真。
参数
c - 要在此列表中测试其存在性的元素。
返回值
如果此列表包含指定元素,则返回真。
抛出异常
ClassCastException - 如果指定元素的类型与此列表不兼容(可选)。
NullPointerException - 如果指定元素为 null 而此列表不允许 null 元素(可选)。
示例
下面是展示 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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP