View RSS Feed

My Java Tips

How to remove an element from a collection

Rate this Entry
by , 11-08-2011 at 05:40 PM (619 Views)
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:




Java 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

Submit "How to remove an element from a collection" to Facebook Submit "How to remove an element from a collection" to Digg Submit "How to remove an element from a collection" to del.icio.us Submit "How to remove an element from a collection" to StumbleUpon Submit "How to remove an element from a collection" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments