Given:.
2. class Square { 3. Square(String c, int h) { color = c; hotness = h; } 4. String color; /*from ww w . j a va 2 s .c om*/ 5. int hotness; 6. public boolean equals(Object o) { 7. if(this == (Square)o) return true; 8. return false; 9. } 10. public String toString() { return color + " " + hotness; } 11. }
If instances of class Square are to be used as keys in a Map, which are true? (Choose all that apply.).
hashCode()
, the code will not compile.equals()
method has been legally overridden.equals()
and hashCode()
contracts.hashCode()
was correctly overridden, it would make retrieving Map entries by key easier.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.