Menu
Topics Index
...
`

Creating CopyOnWriteArrayList and Iterator


If you need explanation Read this topic

If you need Answer Take test on this topic

Creating CopyOnWriteArrayList and Iterator
What will be the output of the following program?
import java.util.*;
import java.util.concurrent.*;

public class CopyOnWriteListTest {
    public static void main(String... l) {
        CopyOnWriteArrayList list = new CopyOnWriteArrayList();
        list.add("Java");
        list.add("Merit");
        Iterator i = list.iterator();
        while (i.hasNext()) {
            i.next(); // LINE A
            list.add("Campus"); // LINE B
        }
        Iterator i2 = list.iterator();
        while (i2.hasNext()) {
            System.out.println(i2.next());
            i2.remove(); // LINE C
        }
    }
}

A. Java
Merit
Campus
B. Java
Merit
Campus
Campus
C. throws Exception at LINE A
D. throws Exception at LINE B
E. throws Exception at LINE C
Topic: Other Advanced Topics In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans is e as we cant remove elements using iteartor

Posted by Pramod Jain    2013-07-23 12:53:18


e is answer since we are removing unknown source here with .i2.remove()

Posted by Karteek Paruchuri    2013-07-23 12:53:27


option e as we cannot modify CopyOnWriteArrayList never changes during the lifetime of the iterator, so interference is impossible ..so The iterator will not reflect additions, removals, or changes to the list since the iterator was created and it throws exception

Posted by Shaik Nyamath    2013-07-23 13:13:12


b

Posted by Aruna Dantu    2013-07-23 15:25:26


Congratulations Pramod Jain. You are this dose winner. Please send us your mobile details and we will process the recharge asap.

Posted by Merit Campus    2013-07-25 01:18:38


hello pramod jain we can remove elements form the list using iterator because there is a metod remove() in the iterator interface your answer may be correct but explanation is wrong

Posted by Ram Reddy Bitla    2013-07-25 04:07:55


@ram reddy : ur correct bt wat i meant was regarding in dis case.. :) as we cannot change the array wen we create list wth copyonwritearraylist... :)

Posted by Pramod Jain    2013-07-25 14:23:57


got rc :) thank u :)

Posted by Pramod Jain    2013-07-30 12:53:13


© meritcampus 2019

All Rights Reserved.

Open In App