Arraylist with iterator

Iterator with ArrayList:
========================

alist.iterator();
while iteration add/remove will gives exception i.e concurrentmodificationException
update wont give any exception.
package com.me.collections;

import java.util.ArrayList;
public class ExceptionDemo {
public static void main(String args[]){
ArrayList books = new ArrayList();
books.add(“C”);
books.add(“Java”);
books.add(“Cobol”);

for(String obj : books) {
System.out.println(obj);
//We are adding element while iterating list
// books.add(“C++”);
// //Exception in thread “main” java.util.ConcurrentModificationException
// at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
// at java.util.ArrayList$Itr.next(Unknown Source)
// at com.me.collections.ExceptionDemo.main(ExceptionDemo.java:11)
// C

books.set(2, “fdsngfds”);

//error
// books.add(“C++”);
//error
// books.remove(“Java”);
}
}
}

Use CopyOnWriteArrayList
and if you want to remove it, do the following:

for (Iterator it = userList.iterator(); it.hasNext() 😉
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}

Advertisements