ZeKai ZeKai - 3 months ago 36
Java Question

Why HashMap.get() return the last position under the same key in array?

public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int complement = target - nums[i];

map.put(nums[i], i);

if(map.containsKey(complement)) {
return new int[] {map.get(complement), i};

throw new IllegalArgumentException("No solution");

public static void main(String[] args) {
int[] array = new int[]{1, 9, 9, 3, 0, 3, 1, 2};
System.out.println(Arrays.toString(twoSum(array, 12)));

Why return [2, 3] instead of [1, 3]?

Does HashMap.get() always return the last value position under multiple same key in array?


Hashmaps work on hashing principle.

When you call put(key, value), the hashcode() method of the provided key is called and accordingly a bucket is reserved in the memory for this hashcode holding the passed value.

If you called again put(key,value) with the same key, then the same hashcode will be generated and hence the hashing function of the map will access the same bucket and update it with the new value object.

So that's why, you should be careful when calling put(key, value) inside a loop in order to prevent this confusion.