Junior — Middle
Is the number 1 a valid key in a HashMap data structure, considering its immutability?
sobes.tech AI
Answer from AI
Yes, the number 1 is a valid key in a HashMap data structure in Java.
Explanation:
- Keys in a
HashMapmust be objects for which thehashCode()andequals()methods are correctly implemented. - In Java, primitive types like
intcannot be keys directly, but their object wrappers, such asInteger, can. - The number
1as anIntegerobject is immutable, which guarantees that its hash code and equality will not change after being placed in aHashMap.
Example:
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "one");
System.out.println(map.get(1)); // Outputs: one
}
}
Thus, using the number 1 (as an Integer object) as a key in a HashMap is completely valid.