2

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?

Community
  • 1
  • 1
Kai Wang
  • 133
  • 5

1 Answers1

3

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);
};
Joni
  • 108,737
  • 14
  • 143
  • 193
  • I've updated the answer to add a possible alternative implementation of Arrays.compare for Java 8 – Joni Aug 11 '20 at 03:51
  • Does that work for Java 7 and under? – Kai Wang Aug 11 '20 at 04:18
  • so how do I get my Java 8 program to work? Where do I place this comparator? – Kai Wang Aug 11 '20 at 04:26
  • For Java 7, you would have to rewrite `arrayComparator` as a class that implements the `Comparator` interface because Java 7 lacks the lambda expression feature. For Java 6 you would have to make even more changes, for Java 5 even more still. But do note that Java 8 came out over 6 years ago – Joni Aug 11 '20 at 04:32
  • `new TreeMap<>(arrayComparator)` – Joni Aug 11 '20 at 04:34