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?