This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am trying to use java.util.HashSet for storing collection of non-duplicate values of my own custom class.
Here is the sample program which I tried.
hashcode called97 hashcode called98 hashcode called97 hashcode called98 hashcode called97 s = [a, a, a, 1, b, b]
The UsingSet class has a single field value and two UsingSet instances are equal if their values are equal.
I dont know how add() method works to compare objects. But from the above output the add() method is not using the overloaded equals method (the print statements are getting not printed) and it adds to set even if attribute value has the same value.
Overloading hashCode() method also doesn't seems to work.
I tried the same with java.util.TreeSet() by passing my own comparator to constructor and it works fine.
Your hashCode() method is based on the name, but equals is based on the id. The behavior of the two methods is therefore inconsistent. In particular, the two objects you're testing with are equals(), but they have different hashCode() values. The HashSet will only call equals() to check for the equality of two objects with the same hashCode().
Campbell Ritchie wrote:Also your equals() method does not test whether the two Objects are of the same class; you can suffer a ClassCastException.
equals() does indeed, although compareTo() does not.
Joined: Jan 27, 2006
Hi Ernest / Campbell,
Thanks for your quick reply.
I changed the hashcode() method and made it consistent with equals() method as below. I am getting the expected results now. Thanks for clarifying the concept regarding equals() and hashcode() methods.