简体   繁体   中英

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. When I restart the application I load them from that file again. However, the Image img variable is constantly changing. That means when I use arrayList.contains(studentA) it's not the same object anymore, so arrayList.remove(studentA) won't work.

Is there an easy way to either: Only check for the name of the student or ignore the Image field when using contains() ?

Yes.

Just implement the equals/hashcode without the Image attribute.

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()

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM