'Using @UniqueElements annotation for a List of Object

I want to add a check for a List of Students List<Student> based on their phone_number.

Student : {
  id, name, rollNo, phone_number
};

I have a Class and in the class all students must have a unique phone number.

Class : {
  classId, name, 
  //Here I want to add @UniqueElements by Hibernate over the field of `phone_number` of `Student`.
  //@UniqueElements 
  List<Student>
}

I tried to find some help in such complex DS but only found examples for Basic DS like List<Integer>.

Can someone help me to find how can I accomplish this task?


Note : Like is there some option for eg: @UniqueElements(validateBy="phone_number") through which I can do this.



Solution 1:[1]

You need override hashCode and equals in class Student

@Override
public int hashCode() {
    return phone_number.hashCode();
}

@Override
public boolean equals(Object obj) {
    if (obj instanceof Student) {
        return phone_number.equals(((Student)obj).phone_number);
    }
    return false;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrey D