Search code examples
javahashmappass-by-referencepass-by-valuecontainskey

Java - containsKey() on HashMap returning null - is it checking for the exact object rather than just a matching key?


I've got a HashMap of Integer[], Integer[]. One of the entries is:

WEIGHTS.put(new Integer[]{0,0,0,0,0}, new Integer[]{20,20,15,15,10,10,5,5});

I then call:

probabilities = WEIGHTS.get(sheriffAndBanditPositions);

where sheriffAndBanditPositions is:

Integer[] sheriffAndBanditPositions = new Integer[]{0,0,0,0,0};

This results in probabilities being null. Why is this? How can I check if a matching Integer[] key is in the HashMap if the above isn't possible? Thanks!


Solution

  • An array doesn't work as key in HashMap, since arrays don't override Object's hashCode and equals methods. containsKey would only return true if you pass the exact same instance you passed to put.

    You can use a List or Set as the key instead of an array.

    For example :

    Map<List<Integer>,Integer[]> WEIGHTS = ...
    WEIGHTS.put(Arrays.asList(new Integer[]{0,0,0,0,0}), new Integer[]{20,20,15,15,10,10,5,5});
    List<Integer> sheriffAndBanditPositions = Arrays.asList(new Integer[]{0,0,0,0,0});
    probabilities = WEIGHTS.get(sheriffAndBanditPositions);