如何檢查 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