我有一个这样的类:
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/