Java OCA OCP Practice Question 3057

Question

Given this code segment:

Set<String> set = new CopyOnWriteArraySet<String>(); // #1
set.add("2");
set.add("1");
Iterator<String> iter = set.iterator();
set.add("3");
set.add("-1");
while(iter.hasNext()) {
    System.out.print(iter.next() + " ");
}

Choose the correct option based on this code segment.

  • a) this code segment prints the following: 2 1
  • b) this code segment the following: 1 2
  • c) this code segment prints the following: -1 1 2 3
  • d) this code segment prints the following: 2 1 3 -1
  • e) this code segment throws a ConcurrentModificationException
  • f) this code segment results in a compiler error in statement #1


a)

Note

this code segment modifies the underlying CopyOnWriteArrayList container object using the add() method.

after adding the elements "2" and "1", the iterator object is created.

after creating this iterator object, two more elements are added, so internally a copy of the underlying container is created due to this modification to the container.

But the iterator still refers to the original container that had two elements.

So, this program results in printing 2 and 1.

If a new iterator is created after adding these four elements, it will iterate over all those four elements.




PreviousNext

Related