Search code examples
javahashmapintegercontainskey

HashMap containsKey returns false for Integer


I have this simple code and i figured out that for the last array number the containsKey method returns always false.

int[] indices = new int[] { 1, 3, 5, 7, 9 };

Map<Integer, Integer> seen = new HashMap<>();

for (int i = 0; i < indices.length - 1; i++) {
    seen.put(indices[i], i);
}

All other true except:

System.out.println("!!!!! " + seen.containsKey(9) );

Also with new

int[] { 1, 3, 5, 7 };

All other true except:

System.out.println("!!!!! " + seen.containsKey(7) );

What is the logic behind this?


Solution

  • You don't put the last element of your indices array in your Map.

    Change

    for (int i = 0; i < indices.length - 1; i++) {
        seen.put(indices[i], i);
    }
    

    to

    for (int i = 0; i < indices.length; i++) {
        seen.put(indices[i], i);
    }