Saturday, August 21, 2010

hashCode() and equals(): Sock.java

Courtesy of Sun Web Learning Center

A programmer is working on a top secret project, and must implement an equals() method to appropriately work with the Sock class's hashCode() method given:


42.  public int hashCode() {
43.    return (size.hashCode() + color.hashCode()) * 17;
44.  }

Which equals method supports that goal?


A    
   
Impossible to determine

B    
   

public boolean equals(Object o) {
Sock s = (Sock) o; 
return size.equals(s.size);  }

C    
   

public boolean equals(Object o) {
Sock s = (Sock) o;
return size.equals(s.size) && color.equals(s.color);  }
   

D    
   

public boolean equals(Object o) {
Sock s = (Sock) o; 
return color.equals(s.color);  }


C is correct because the equals() method must test both size and color, since the hashCode() method uses them both in its hash formula.

No comments:

Post a Comment