Java HashMap<int[], Integer>

Viewed 633

I want to map an array to an ArrayList such that two arrays mapped to the same thing if they are identical.

This outputs null:

HashMap<int[], Integer> map = new HashMap<>();
map.put(new int[1], 0);
System.out.println(map.get(new int[1]));

And I want the output to be 0. Is there an easy way to do this? Should I use TreeMap? How do I do this in TreeMap?

1 Answers

Using a TreeMap works, if you pass in a Comparator instance that can be used with arrays. Luckily the standard library already has a method you can use Arrays.compare:

TreeMap<int[], Integer> map = new TreeMap<>(Arrays::compare);
map.put(new int[1], 1);
System.out.println(map.get(new int[1])); // output: 1

That said, using a mutable object such as an array as the map key is not a very good idea. If you accidentally change an array used as a key, the map will stop working as expected.

The reason why HashMap will not work is because arrays don't implement a hashCode or equals method based on the array contents. They are based on the object identity instead.


Arrays.compare was added in Java 9. For Java 8 you'll need to write the Comparator yourself. Here is one option:

Comparator<int[]> arrayComparator = (a, b) -> {
    for (int i = 0; i < Math.min(a.length, b.length); i++) {
        int compare = Integer.compare(a[i], b[i]);
        if (compare != 0) return compare;
    }
    return Integer.compare(a.length, b.length);
};
Related