Multiple choice technology programming languages

Given: 11. public class Key { 12. private long id1; 13. private long 1d2; 14. 15. // class Key methods 16. } A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)

  1. public int hashCode()

  2. public boolean equals(Key k)

  3. public int compareTo(Object o)

  4. public boolean equals(Object o)

  5. public boolean compareTo(Key k)

Reveal answer Fill a bubble to check yourself
A,D Correct answer
Explanation

For a class to work correctly as a HashMap key, it must override hashCode() and equals(Object). HashMap uses hashCode() to bucket entries and equals() to compare keys. The equals() method signature must be 'public boolean equals(Object o)' - overriding Object.equals() requires the Object parameter type, not Key. Option B's 'equals(Key k)' would be overloading, not overriding. Options A and D are correct - hashCode() and equals(Object) must both be overridden consistently.

AI explanation

To assure that the Key class works correctly as a key in a java.util.HashMap, two methods should be overridden: hashCode() and equals(Object o).

A. public int hashCode() - This method needs to be overridden to provide a unique hash code for each Key object. The HashMap uses the hash code to determine the bucket location for storing and retrieving objects.

D. public boolean equals(Object o) - This method needs to be overridden to define the equality comparison for Key objects. The HashMap uses the equals() method to check if two keys are equal or not.

Options B, C, and E are incorrect:

B. public boolean equals(Key k) - This method is not the correct signature for the equals() method. The equals() method should take an Object parameter, not a specific type.

C. public int compareTo(Object o) - This method is not necessary for the Key class to work as a key in a HashMap. The compareTo() method is used for sorting objects and is not relevant to the HashMap implementation.

E. public boolean compareTo(Key k) - This method is not the correct signature for the compareTo() method. The compareTo() method should take an Object parameter, not a specific type.

Therefore, the correct answer is options A and D.