How to remove an element from a collection

24 March 2007

Collections in Java include so many interesting features. As the number of features increase there arise the possibility of incorrect usage. Here we discuss such an issue while removing an object from a Collection. Exception throw is “Concurrentmodificationexception” .

Code:

package test;import java.util.ArrayList;
 
import java.util.Iterator;
 
import java.util.List;
 
public class ListExample {
 
 List list;
 
public ListExample() {
 
 	list = new ArrayList();
 
 }
 
private List getList() {
 
 	return list;
 
 }
 
private void remove() {
 
 }
 
private void add() {
 
}
 
public static void main(String[] args) {
 
 	ListExample lExam = new ListExample();
 
 	List tempList = lExam.getList();
 
 	tempList.add("1");
 
 	tempList.add("2");
 
 	tempList.add("3");
 
 	Iterator iterator = lExam.getList().iterator();
 
 	while (iterator.hasNext()) {
 
String i = (String) iterator.next();
 
 		System.out.println(i);
 
 		if (i == "1") {
 
 			tempList.remove(0);
 
//				iterator.remove();
 
 		}
 
}
 
 	iterator = lExam.getList().iterator();
 
 	while (iterator.hasNext()) {
 
 		String i = (String) iterator.next();
 
 		System.out.println("after remove " + i);
 
 	}
 
}
 
}

Here is output of program


Exception in thread “main” java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)
at test.ListExample.main(ListExample.java:33)

The reason is that if you are iterating over a collection using “Iterator” then you should use “iterator.remove()” that will remove last element which “iterator” iterated recently. So always remember to use “iterator” to remove an element if you are iterating over that collection already. On changing to “iterator.remove” we get output

2

3

after remove 2

after remove 3

del.icio.us:How to remove an element from a collection  digg:How to remove an element from a collection  spurl:How to remove an element from a collection  wists:How to remove an element from a collection  simpy:How to remove an element from a collection  newsvine:How to remove an element from a collection  blinklist:How to remove an element from a collection  furl:How to remove an element from a collection  reddit:How to remove an element from a collection  fark:How to remove an element from a collection  blogmarks:How to remove an element from a collection  Y!:How to remove an element from a collection  smarking:How to remove an element from a collection  magnolia:How to remove an element from a collection  segnalo:How to remove an element from a collection  gifttagging:How to remove an element from a collection

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: How to remove an element from a collection

Leave a Reply