How to remove an element from a collection
24 March 2007Collections 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
Related Posts:
- Removing elements from a List
- Enhanced for-loop (Java 5.0)
- Introduction To Collections In Java
- Hibernate Filters - II
- Enumerations and Iterators
- More on Collection FrameWork
- Java performance Issues (III) - Garbage collection
- Eclipse project - Extension page
- Subtyping
- Sharing setUp() and tearDown() code for all tests - II
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