Java Reference
In-Depth Information
< Day Day Up >
Puzzle 58: Making a Hash of It
This puzzle attempts to learn from the mistakes of the previous one. Again the program consists of
a Name class and a main method that puts a name into a hash set and checks whether the set contains
the name. This time, however, the Name class does override the hashCode method. What does this
program print?
import java.util.*;
public class Name {
private final String first, last;
public Name(String first, String last) {
this.first = first; this.last = last;
}
public boolean equals(Name n) {
return n.first.equals(first) && n.last.equals(last);
}
public int hashCode() {
return 31 * first.hashCode() + last.hashCode();
}
public static void main(String[] args) {
Set<Name> s = new HashSet<Name>();
s.add(new Name("Donald", "Duck"));
 
 
Search WWH ::




Custom Search