Java OCA OCP Practice Question 2608

Question

Consider the following program:

import java.util.*;

class Main {/*from   ww w.  ja v a  2s  .c  o  m*/
        public static void main(String []args) {
                Set<String> set = new TreeSet<String>();
                set.add("S");
                set.add("R");
                Iterator<String> iter = set.iterator();
                set.add("P");
                set.add("Q");
                while(iter.hasNext()) {
                        System.out.print(iter.next() + " ");
                }
        }
}

Which one of the following options correctly describes the behavior of this program?

  • a) The program prints the following: S R P Q.
  • b) The program prints the following: P Q R S.
  • c) The program prints the following: S R.
  • d) The program prints the following: R S.
  • e) The program throws a ConcurrentModificationException.


e)

Note

From the documentation of TreeSet: "The iterators returned by this class's iterator method are fail-fast : if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.".

This program modifies the underlying TreeSet container object using the add() method using the earlier iterator.

So, this program throws a ConcurrentModificationException.




PreviousNext

Related