Junior — Middle
What prevents the use of primitive data types as keys in data structures?
sobes.tech AI
Answer from AI
In Java, primitive data types (int, char, boolean, etc.) cannot be used directly as keys in data structures like HashMap because these structures work with objects, not primitives.
Reasons:
- Lack of object methods: primitives do not have methods like
hashCode()andequals(), which are necessary for the correct functioning of keys in hash-based structures. - Autoboxing: Java automatically converts primitives to their corresponding wrapper classes (
Integer,Character, etc.), which are objects and implement the required methods.
Therefore, to use primitive values as keys, they need to be boxed into wrapper objects.
Example:
Map<Integer, String> map = new HashMap<>();
int key = 5;
map.put(key, "value"); // key is automatically boxed into Integer