Junior
Can a primitive data type be a key in a HashMap collection?
sobes.tech AI
Answer from AI
Yes, primitive data types can be used as keys in a HashMap.
This involves automatic conversion of the primitive type to its corresponding wrapper class (autoboxing). For example, int is converted to Integer, long to Long, and so on.
HashMap uses the hashCode() and equals() methods to determine key uniqueness. Wrapper types (such as Integer, Long, String) correctly implement these methods, allowing them to serve as keys.
// Example of using int as a key in HashMap
Map<Integer, String> myMap = new HashMap<>();
myMap.put(10, "Ten"); // Autoboxing int 10 to Integer
myMap.put(20, "Twenty"); // Autoboxing int 20 to Integer
// Example of retrieving a value with a primitive key
String value = myMap.get(10); // Autoboxing int 10 to Integer for lookup
// value will be "Ten"