如何在 Java 中检查 ArrayList 是否包含某个项目?

javaobject oriented programmingprogramming更新于 2025/1/5 5:32:17

您可以使用 List 接口的 contains() 方法来检查列表中是否存在某个对象。

contains() 方法

boolean contains(Object o)

如果此列表包含指定元素,则返回 true。更正式地说,当且仅当此列表包含至少一个元素 e,并且 (o==null ? e==null : o.equals(e)) 时,才返回 true。

参数

  • c −要测试此列表中是否存在的元素。

返回

如果此列表包含指定元素,则返回 True。

抛出

  • 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.

相关文章


有用资源