Q9. What is wring with this code?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class WhatIsWrong { public static void main(String args[]) { List<String> myList = new ArrayList<String>(); myList.add("Java"); myList.add("JEE"); myList.add("XML"); Iterator<String> it = myList.iterator(); while (it.hasNext()) { String value = it.next(); System.out.println("List Value:" + value); if (value.equals("Java")) { myList.remove(value); } } } } |
A9. throws a Runtime exception called “java.util.ConcurrentModificationException” The output will be:
|
1 2 3 4 5 6 |
List Value:Java Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886) at java.util.ArrayList$Itr.next(ArrayList.java:836) at WhatIsWrong.main(WhatIsWrong.java:17) |
Fix 1: Use iterator.remove() instead of collection.remove
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class WhatIsWrong { public static void main(String args[]) { List<String> myList = new ArrayList<String>(); myList.add("Java"); myList.add("JEE"); myList.add("XML"); Iterator<String> it = myList.iterator(); while (it.hasNext()) { String value = it.next(); System.out.println("List Value:" + value); if (value.equals("Java")) { it.remove(); //FIX } } } } |
Output:
|
1 2 3 4 |
List Value:Java List Value:JEE List Value:XML |
Fix 2: Use java.util.concurrent classes like CopyOnWriteArrayList
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class WhatIsWrong { public static void main(String args[]) { List<String> myList = new CopyOnWriteArrayList<String>(); //FIX myList.add("Java"); myList.add("JEE"); myList.add("XML"); Iterator<String> it = myList.iterator(); while (it.hasNext()) { String value = it.next(); System.out.println("List Value:" + value); if (value.equals("Java")) { myList.remove(value); } } } } |
Output:
|
1 2 3 4 |
List Value:Java List Value:JEE List Value:XML |
…