[英]Java ArrayList, how to ignore a value from the object when using contains()
I have a class like that: 我有一个这样的课:
public class Student implements Serializable{
private String name;
private int age;
private Image img;
}
I store a few students in an ArrayList and write them to a file. 我将一些学生存储在ArrayList中并将它们写入文件。 When I restart the application I load them from that file again.
当我重新启动应用程序时,我再次从该文件加载它们。 However, the
Image img
variable is constantly changing. 但是,
Image img
变量不断变化。 That means when I use arrayList.contains(studentA)
it's not the same object anymore, so arrayList.remove(studentA)
won't work. 这意味着当我使用
arrayList.contains(studentA)
它不再是同一个对象,所以arrayList.remove(studentA)
将不起作用。
Is there an easy way to either: Only check for the name of the student or ignore the Image
field when using contains()
? 是否有一种简单的方法:只检查学生的名字或在使用
contains()
时忽略Image
字段?
Yes. 是。
Just implement the equals/hashcode without the Image attribute. 只需实现没有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);
}
}
Use JAVA Stream API for fun with lists without contains() 使用JAVA Stream API可以获得没有contains()的列表的乐趣
public static void main(String[] args) {
List<Student> studentBaseList = Arrays.asList(
new Student("Kent", 22, null),
new Student("Jack", 25, null),
new Student("Rick", 27, null)
);
List<Student> studentList = new ArrayList<>(studentBaseList);
String NAME_FOR_SEARCH = "Jack";
// Remove student with name Jack from studentList
studentList.removeIf( student -> NAME_FOR_SEARCH.equals(student.getName()));
System.out.println(studentList);
List<Student> studentList2 = new ArrayList<>(studentBaseList);
// Check if student with name Jack present in the list
boolean isPresentStudentWithNameJack
= studentList2.stream().anyMatch(student -> NAME_FOR_SEARCH.equals(student.getName()));
System.out.println(isPresentStudentWithNameJack);
List<Student> studentList3 = new ArrayList<>(studentBaseList);
// Filter students with name Jack and create new list with students with name Jack.
List<Student> onlyJackStudents = studentList3.stream()
.filter(student -> NAME_FOR_SEARCH.equals(student.getName())).collect(Collectors.toList());
System.out.println(onlyJackStudents);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.