-1

I have two sets (LinkedHashSet) of a custom objects which overrides the hashCode() and equals() methods.

When comparing these two sets the equal() method fails even though the hash codes are the same.

    System.out.println("cmContacts.equals(cm2Contacts):" + cmContacts.equals(cm2Contacts));
    System.out.println("cm2Contacts.equals(cmContacts):" + cm2Contacts.equals(cmContacts));
    System.out.println("compare hash codes:" + ( cm2Contacts.hashCode() == cmContacts.hashCode() ) );        

This returns:

cmContacts.equals(cm2Contacts):false

cm2Contacts.equals(cmContacts):false

compare hash codes:true

According to the documentation if the hash codes are the same the equals method should return true.

The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash code of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of Object.hashCode().

https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#equals(java.lang.Object)

Any ideas why this is happening?

DavidA
  • 402
  • 3
  • 12

2 Answers2

5

You've got it backwards: if two objects are equal, they must have the same hash code. Having the same hash code does not imply that the objects should be equal.

Joni
  • 108,737
  • 14
  • 143
  • 193
1

Same hashcode() does not mean equals.

You can compare that to ZipCode. You and your neighbhour have the same but are not the same.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89