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.
OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
Harnoor Singh wrote:I think point C is correct. We have neither modified the equals() nor hashcode() method. So it can find the correct entry from map.
Jeane Lindford wrote:
Harnoor Singh wrote:I think point C is correct. We have neither modified the equals() nor hashcode() method. So it can find the correct entry from map.
only with a reference variable used to put the item on the map, i`m right? otherwise, no way to find it
Harnoor Singh wrote:
Reference variable will not play any part. The key will be converted into hashcode and that hascode will be used to access the value from bucket/array.
Piyush
Piyush Joshi wrote:
If you try to find a key in a hashmap then first it will get the hashcode of the given object to find the right bucket. But inside that bucket you can have many keys. To find the correct key it then uses the equals() method to compare each key in bucket with the given object.
So if you override the equals method in a way as in the given example, then to find the key, you need the reference to the original object you used to put the key in.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |