the question on page 101/102:
If instances of class Chilis are to be used as keys in a Map, which are true? (Choose all that
apply.)
A. Without overriding hashCode(), the code will not compile.
B. As it stands, the equals() method has been legally overridden.
C. It’s possible for such keys to find the correct entries in the Map.
D. It’s NOT possible for such keys to find the correct entries in the Map.
E. As it stands, the Chilis class legally supports the equals() and hashCode() contracts.
F. If hashCode() was correctly overridden, it would make retrieving Map entries by key easier.
The correction from the book:
B, C, and E are correct. If a class does NOT override equals() and hashCode(), class
Object provides a default implementation. The default implementation’s logic is that only
two references to THE SAME OBJECT will be considered equal.
Given that, it might appear that equals() has been overridden, but in practice this
overridden equals() method performs exactly as the default method performs. Therefore,
the equals() and hashCode() methods will support their contracts, although it will be
hard for a programmer to use this class for keys in a Map.
A is incorrect because the code compiles. D is incorrect based on the above. F is incorrect
because in practice equals() hasn’t really been overridden.
I disagree with:
C - if hashCode is not overriden, every Chilis will be placed in a distinct bucket, and so, even if the equals is overriden correctly, you will not be able to find that object again without know the correct bucket number (only if you still have a reference variable that you used to put that Chilis in the map,... ok.. this makes C ok , but, if I assume that a chilis will be putted like "map.put(new Chilis(arg1, arg2))"?)
F - the quote " it would make retrieving Map entries by key easier" makes you think about an easy and simple modification on equals.. if the hashcode was correctly overriden, with a simple and easy modification on equals would make the code fine
this question is so abstract to me..