Java ArrayList,如何在使用 contains() 时忽略对象中的值

标签 java list arraylist data-structures

我有一个这样的类:

public class Student implements Serializable{
  private String name;
  private int age;
  private Image img;
}

我将几个学生存储在一个 ArrayList 中并将它们写入一个文件。当我重新启动应用程序时,我会再次从该文件加载它们。但是,Image img 变量是不断变化的。这意味着当我使用 arrayList.contains(studentA) 时,它不再是同一个对象,因此 arrayList.remove(studentA) 将不起作用。

是否有一种简单的方法:只检查学生的姓名或在使用 contains() 时忽略 Image 字段?

最佳答案

是的。

只需实现没有 Image 属性的 equals/hashcode。

public class Student implements Serializable {

    private String name;
    private int age;
    private Image img;

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }

}

关于Java ArrayList,如何在使用 contains() 时忽略对象中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244585/

相关文章:

java - 如何解决 StackOverflow 错误?

java - 实现列式加密技术?

java - 发送和接收来自同一类(class)的邮件?

python - 如何获取for循环的第一个对象

list - Scala将Collection转换为Key-key的最佳方法? (第二变种)

C# 将 ArrayList 转换为字符串列表?

Java问题,如何从未知对象中获取方法的值

java - 如何修复 "double printing when I clicked twice on the pretty dialog button"

python - 在列表中查找列表中的周围数字 Python

java - Java 中的递归函数不向 ArrayList 添加项目