Java OCA OCP Practice Question 1963

Question

Given the original array, how many of the following for statements result in an exception at runtime, assuming each is executed independently?.

List<Integer> original = new ArrayList<>(Arrays.asList(1,2,3,4,5)); 
  
List<Integer> copy1 = new CopyOnWriteArrayList<>(original); 
for(Integer w : copy1) 
   copy1.remove(w); //from   w ww.j av a  2s . co m
  
List<Integer> copy2 = Collections.synchronizedList(original); 
for(Integer w : copy2) 
   copy2.remove(w); 
  
List<Integer> copy3 = new ArrayList<>(original); 
for(Integer w : copy3) 
   copy3.remove(w); 
  
Queue<Integer> copy4 = new ConcurrentLinkedQueue<>(original); 
for(Integer w : copy4) 
   copy4.remove(w); 
  • A. Zero
  • B. One
  • C. Two
  • D. Three


C.

Note

CopyOnWriteArrayList makes a copy of the array every time it is modified, preserving the original list of values the iterator is using, even as the array is modified.

The for loop using copy1 does not throw an exception at runtime.

On the other hand, the for loops using copy2 and copy3 both throw ConcurrentModificationException at runtime since neither allows modification while they are being iterated upon.

The ConcurrentLinkedQueue used in copy4 completes without throwing an exception at runtime.

The Concurrent classes order read/write access such that access to the class is consistent across all threads and processes, while the synchronized classes do not.

Because exactly two of the for statements produce exceptions at runtime, Option C is the correct answer.




PreviousNext

Related