0

I have a doctor object and each object has a unique attribute "docMobile"(primary key). I made two different LinkedHashSets (doctorsByLoc & doctorsByAvail) of doctors. Now when i do a

doctorsByLoc.retainAll(doctorsByAvail) 

on the two sets it deletes all the elements even though both have the same doctors.

I have implemented hashCode() Method in my doctor class. I also printed the sets individually to check in the sets have same elements.

public class Doctor{
    String docName;
    long docMobile;
    String docLocation;
    int docDays;

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

Then somewhere in a servlet something like this happens

public static void main(String[] args){
    Set<Doctor> doctorsByLoc = new LinkedHashSet<>();
    Set<Doctor> doctorsByAvail = new LinkedHashSet<>();

    doctorsByLoc.add(d1);
    doctorsByLoc.add(d2);
    doctorsByLoc.add(d3);

    doctorsByAvail.add(d1);
    doctorsByAvail.add(d2);
    doctorsByAvail.add(d3);

    System.out.println("Before retain All "+doctorsByLoc.size());
    for(Doctor d:doctorsByLoc){ 
        System.out.println(d.getdocName());
    }
    doctorsByLoc.retainAll(doctorsByAvail);
    System.out.println("After retain All"+doctorsByLoc.size());
    for(Doctor d:doctorsByLoc){ 
        System.out.println(d.getdocName());
    }
}        


Actual output:
Before retain All 3
d1's name
d2's name
d3's name
After retain All 0

How can i fix my hashcode method so that the doctors remain. I have tried printing the hashcode before returning it and I got pairs of similar hashcode as output.

Sanath Kumar
  • 163
  • 1
  • 12

1 Answers1

3

You did not override equals correctly. You should be overriding it as follows:

@Override
public boolean equals (Object other) // Not "Doctor other"
{
    // implementation here
}
Joe C
  • 15,324
  • 8
  • 38
  • 50