Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium

Question 101

Question ID: UKOCP68250


Consider below code of Test.java file:


What will be the result of compiling and executing Test class?

  • A [Walnut, Apricot, Almond, Date]
  • B [Walnut, Date]
  • C An exception is thrown at runtime
  • D Compilation error
Reveal correct answer

Correct answer: C

Explanation

UKOCP68250:

ConcurrentModificationException exception may be thrown for following condition:

1. Collection is being iterated using Iterator/ListIterator or by using for-each loop.

And

2. Execution of Iterator.next(), Iterator.remove(), ListIterator.previous(), ListIterator.set(E) & ListIterator.add(E) methods. These methods may throw java.util.ConcurrentModificationException in case Collection had been modified by means other than the iterator itself, such as Collection.add(E) or Collection.remove(Object) or List.remove(int) etc.


PLEASE NOTE: for-each loop internally implements Iterator and invokes hasNext() and next() methods.


For the given code, 'dryFruits' list is being iterated using for-each loop (internally as an Iterator).

hasNext() method of Iterator has following implementation:

Where cursor is the index of next element to return and initially it is 0.


1st Iteration: cursor = 0, size = 4, hasNext() returns true. iterator.next() increments the cursor by 1 and returns "Walnut".

2nd Iteration: cursor = 1, size = 4, hasNext() returns true. iterator.next() increments the cursor by 1 and returns "Apricot". As "Apricot" starts with "A", hence dryFruits.remove(dryFruit) removes "Apricot" from the list and hence reducing the list's size by 1, size becomes 3.

3rd Iteration: cursor = 2, size = 3, hasNext() returns true. iterator.next() method throws java.util.ConcurrentModificationException.


If you want to successfully remove the items from ArrayList, while using Iterator or ListIterator, then use Iterator.remove() or ListIterator.remove() method and NOT List.remove(...) method. Using List.remove(...) method while iterating the list (using the Iterator/ListIterator or for-each) may throw java.util.ConcurrentModificationException.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need