Junior — Middle
Can a primitive object act as a key when using HashMap?
sobes.tech AI
Answer from AI
In Java, primitive types (int, boolean, char, etc.) cannot directly serve as keys in a HashMap because the key must be an object. However, thanks to autoboxing, primitives are automatically converted into their corresponding wrapper objects (for example, int to Integer), which can then be used as keys.
Example:
HashMap<Integer, String> map = new HashMap<>();
int key = 5;
map.put(key, "value"); // key is automatically boxed into Integer
Thus, a primitive object in the strict sense cannot be a key, but its object wrapper can.