Java Reference
In-Depth Information
System.out.println(
s.contains(new Name("Donald", "Duck")));
}
}
Solution 58: Making a Hash of It
As in Puzzle 57 , the main method of this program creates two Name instances, both representing the
same name. This time it, happens to be Donald Duck rather than Mickey Mouse, but that shouldn't
make much difference. Again, the main method puts the first instance into a hash set and then
checks whether the set contains the second. This time, the hashCode method is clearly correct, so it
looks as though the program ought to print TRue . Once again, appearances are deceiving: It always
prints false . What's wrong this time?
The flaw in this program is similar to the one in Puzzle 57 . In that puzzle, Name overrides the
equals method but fails to override hashCode ; in this puzzle, Name overrides the hashCode method
but fails to override equals . That is not to say that Name doesn't declare an equals method; it does,
but it's the wrong one. The Name class declares an equals method whose argument is of type Name
rather than Object . The author of this class probably intended to override the equals method but
mistakenly overloaded it [JLS 8.4.8.1, 8.4.9].
The HashSet class uses the equals(Object) method to test elements for equality; it is of no
consequence to HashSet that Name declares an equals(Name) method. So where does Name get its
equals(Object) method? It is inherited from Object . This method returns true only if its
argument and the object on which it is invoked are one and the same. The main method of our
program inserts one Name instance into the hash set and tests for the presence of another, so the test
is guaranteed to return false . To us, both instances may represent the wonderful waterfowl, but to
the hash map, they're just two unequal objects.
Fixing the program is as simple as replacing the overloaded equals method with the overriding one
found in Puzzle 57 . With this equals method, the program prints TRue as expected:
public boolean equals(Object o) {
if (!(o instanceof Name))
 
 
Search WWH ::




Custom Search