Given:
2. class Square { 3. Square(String c, int h) { color = c; hotness = h; } 4. String color; //from www. j ava 2 s . c o m 5. private int hotness; 6. public boolean equals(Object o) { 7. Square c = (Square)o; 8. if(color.equals(c.color) && (hotness == c.hotness)) return true; 9. return false; 10. } 11. // insert code here 12. }
Which, inserted independently at line 11, fulfill the equals()
and hashCode()
contract for Square? (Choose all that apply.).
hashCode()
{ return 7; }hashCode()
{ return hotness; }hashCode()
{ return color.length()
; }hashCode()
{ return (int)(Math.random()
* 200); }hashCode()
{ return (color.length()
+ hotness); }A, B, C, and E are correct.
They all guarantee that two objects that equals()
says are equal, will return the same integer from hashCode()
.
The fact that hotness is private has no bearing on the legality or effectiveness of the hashCode()
method.
D is incorrect because the random()
method will usually return different integers for two objects that equals()
says are equal.
E is correct.
Of all the legal hashCode()
methods, this one will create the most hash buckets, which will lead to the fastest retrieval times.