Middle+
What are the requirements for keys and values in HashMap?
sobes.tech AI
Answer from AI
In Java, HashMap requires that keys correctly implement the hashCode() and equals() methods. This is necessary for proper distribution of elements across buckets and for correct key lookup.
Requirements for keys:
- The
hashCode()method must be stable and return the same value for the same object throughout its lifetime in theHashMap. - The
equals()method must correctly compare objects for equality. - Keys should be immutable if used as keys, to avoid violating the
hashCode/equalscontract.
Values in a HashMap can be any objects, including null. Unlike keys, values do not participate in hash code calculation or key comparison, so there are no special requirements for them.
Example:
Map<String, Integer> map = new HashMap<>();
map.put("key", 123); // key is a String that correctly implements hashCode and equals