0

In my program, I wanted to use a HashMap of Integer[]s, but I was having trouble retrieving the data. After further investigation, I found that this, without anything else in the program, prints null.

HashMap<Integer[], Integer> a = new HashMap<Integer[], Integer>();
Integer[] b = {5, 7};
Integer[] c = {5, 7};
a.put(b, 2);
System.out.println(why.get(c));

I don't want to have to iterate through the HashMap with a.keySet() if I don't have to. Is there any other way to achieve the desired result?

  • You haven't specified what behaviour you expect from this code? And also `why` is not defined anywhere. – tuxdna Jul 02 '15 at 19:43

2 Answers2

3

Arrays are stored in the map based on a hash that's calculated from the object itself and not based on the values contained within (the same behavior happens when using == and the equals method with arrays).

Your key should be a collection that properly implements .equals and .hashCode rather than a plain array.

Alan
  • 468
  • 3
  • 9
0

Check this code for the un/desired behaviour:

// this is apparently not desired behaviour
{
    System.out.println("NOT DESIRED BEHAVIOUR");
    HashMap<Integer[], Integer> a = new HashMap<Integer[], Integer>();
    Integer[] b = { 5, 7 };
    Integer[] c = { 5, 7 };
    a.put(b, 2);
    System.out.println(a.get(c));
    System.out.println();
}
// this is the desired behaviour
{
    System.out.println("DESIRED BEHAVIOUR");
    HashMap<List<Integer>, Integer> a = new HashMap<List<Integer>, Integer>();
    int arr1[] = { 5, 7 };
    List<Integer> b = new ArrayList<Integer>();
    for (int x : arr1)
        b.add(x);

    int arr2[] = { 5, 7 };
    List<Integer> c = new ArrayList<Integer>();
    for (int x : arr2)
        c.add(x);

    System.out.println("b: " + b);
    System.out.println("c: " + c);
    a.put(b, 2);
    System.out.println(a.get(c));
    System.out.println();
}

OUTPUT:

NOT DESIRED BEHAVIOUR
null

DESIRED BEHAVIOUR
b: [5, 7]
c: [5, 7]
2

You may also want to check these two question:

tuxdna
  • 8,257
  • 4
  • 43
  • 61