2

I am revising concepts of HashMap and just wanted to check how linked list implementation of each bucket of Entry class works.

public static void main(String[] args) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(1, 1);
    map.put(1, 2);
    map.put(1, 3);
    map.put(2, 1);
    map.put(2, 2);
    System.out.println(map.values());
}

}

Above code prints 3,2. Shouldn't it print 1, 2, 3, 1, 2.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ashutosh
  • 75
  • 1
  • 10

1 Answers1

2

You inserted the values 1, 2, 3 into key 1, and the values 1, 2 into key 2. Each time you insert a value into a key, you overwrite the value which previously existed at the key, assuming there were a previous value. So, your code is functionally identical to this:

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 3);
map.put(2, 2);

That is, only the latest key-value assignments actually "stick."

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360