In Main
Student st=new Student(1,"snack");
Student st1=new Student(2,"jack");
Student st2=new Student(2,"jack");
Set<Student> hs=new HashSet<Student>();
hs.add(st);
hs.add(st1);
hs.add(st2);
System.out.println(hs);
O/P:[1 snack, 2 jack, 2 jack]
In Student
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.id;
}
@Override
public boolean equals(Student obj) {
if(this.id==obj.id)
return false;
else
return true;
My objective is not to allow student who has the same id..name can be the same. Please provide details how HashSet checks which element is a duplicate? All I know that HashSet returns true or false based on hashcode() and equals() method. What works in back end?