0

Let's say that I've got a Hashmap and I would like array of two Integers to actually be the key of each value. I can't figure out how to get the correct value back. It should already be stored in the Hashmap

public class Mapky {
    public static void main(String[] args) {
        HashMap<Integer[], String> mapka = new HashMap<>();
        mapka.put(new Integer[]{10,23}, "Hello");
        System.out.println(mapka.get(new Integer[]{10,23}));
    }
}

Also why does this

System.out.println(new Integer[]{10,23}.equals(new Integer[]{10,23}));

return false?

TiiJ7
  • 3,332
  • 5
  • 25
  • 37
Martin Lukas
  • 314
  • 5
  • 17
  • 1
    You can't. Arrays are only ever equal to themselves. Create a proper class with hashCode and equals(). or at the very least, use a List. Avoid arrays in general. – JB Nizet Mar 20 '19 at 12:35

1 Answers1

1

You have to provide a reference to the key.
If you create a new Integer[]{10, 23}, you will create a different one which has the same value but is not the key.
Do it like this:

public static void main(String[] args) {
    Map<Integer[], String> mapka = new HashMap<>();
    Integer[] key = new Integer[]{10, 23};
    mapka.put(key, "Hello");
    System.out.println(mapka.get(key));
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • I can't even answer because while I was typing someone marked this as duplicate. My answer is more generally applicable, and similar to [Genzer's answer](https://stackoverflow.com/a/15576366/1052284) on the 'duplicated' question. – Mark Jeronimus Mar 20 '19 at 12:44