Senior
Is it possible to use an array as a key in a HashMap? Why is this a bad idea?
sobes.tech AI
Answer from AI
In Java, arrays inherit the hashCode() and equals() methods from the Object class, which do not consider the array's contents but are based on the memory address. Therefore, if you use an array as a key in a HashMap, the keys will be compared by reference, not by content, which usually does not match the expected behavior.
This is a bad idea because:
- Two arrays with the same elements will be considered different keys.
- This can lead to unexpected errors and difficulties in debugging.
If you need to use an array as a key, it is better to use a wrapper, such as List, or use Arrays.hashCode() and Arrays.equals() to implement correct hashCode and equals methods.
Example of the problem:
int[] key1 = {1, 2, 3};
int[] key2 = {1, 2, 3};
HashMap<int[], String> map = new HashMap<>();
map.put(key1, "value1");
System.out.println(map.get(key2)); // null, even though the contents of key1 and key2 are the same