-2

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?

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
SUVAM ROY
  • 103
  • 1
  • 10

1 Answers1

4

You got the condition reversed. You have to return true if two students have the same id.

if(this.id == obj.id)
    return true;
else
    return false;

You are not overriding the equals in the Object class(Object.equals). The equals takes an Object as a parameter and not Student.

Here's a way you can do it.

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Student))
        return false;
    if (obj == this)
        return true;
    return this.id == ((Student) obj).id;
}
Thiyagu
  • 17,362
  • 5
  • 42
  • 79