0
    ConcurrentHashMap<String, Integer> hm = new ConcurrentHashMap<>();
    hm.put("1", 1);
    hm.put("2", 2);
    hm.put("3", 3);
    Iterator<String> itr = hm.keySet().iterator();
    while(itr.hasNext()){
        String key = itr.next();
        System.out.println(key + " : " + hm.get(key));
        hm.put("4", 4);
    }
    System.out.println(hm);

    ConcurrentHashMap<String, Integer> hm1 = new ConcurrentHashMap<>();
    hm1.put("One", 1);
    hm1.put("Two", 2);
    hm1.put("Three", 3);
    Iterator<String> itr1 = hm1.keySet().iterator();
    while(itr1.hasNext()){
        String key = itr1.next();
        System.out.println(key + " : " + hm1.get(key));
        hm1.put("Four", 4);
    }
    System.out.println(hm1);

Output: 1 : 1 2 : 2 3 : 3 4 : 4 {1=1, 2=2, 3=3, 4=4} One : 1 Two : 2 Three : 3 {One=1, Four=4, Two=2, Three=3}

Why so?

VKN
  • 1
  • 2

1 Answers1

0

The interator() call has this documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#iterator--
"The elements are returned in no particular order"

hm.put("4", 4)
Adds it to the end of the list (by chance?)

hm1.put("Four", 4)
Adds it between One and Four. However the next() operator is evidently already past this point in the Iterator, so the next call to next() is already at Two=2.

Answer:
Changing an unordered list as you're iterating over the same list is not a good idea.

David
  • 1,743
  • 1
  • 18
  • 25