How to remove items from Collections while iterating through it?

I was trying to remove items from Java Collection using for loop but when the line

 items.remove()  

executes, it gives me the exception

 Exception in thread "main" java.util.ConcurrentModificationException  

My Code was as follows,

 List<String> items = new ArrayList<String>();  
 items.add("1");  
 items.add("2");  
 items.add("3");  
 items.add("4");  
 for(int i=0; i<items.size(); i++)  
 {  
      String item = (String)items.get(i);  
      if(i==3)  
           items.remove(i);  
 }  
 System.out.println(items);  

To solve this issue I got an solution as follows,

An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method.

The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration. The remove method removes the last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.

Note: Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Reference: Oracle Java Documentation

Use Iterator instead of the for-each construct when you need to:

Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
Iterate over multiple collections in parallel.
The following method shows you how to use an Iterator to filter an arbitrary Collection — that is, traverse the collection removing specific elements.

Solution:

 List<String> items = new ArrayList<String>();  
 items.add("1");  
 items.add("2");  
 items.add("3");  
 items.add("4");  
 for(Iterator<String> itr = items.iterator();itr.hasNext();)  
 {  
      String item = itr.next();  
      if(i==3)  
           itr.remove(i);  
 }  
 System.out.println(items);  


This simple piece of code is polymorphic, which means that it works for any Collection regardless of implementation. This example demonstrates how easy it is to write a polymorphic algorithm using the Java Collections Framework.

Comments

Popular posts from this blog

How to get context path in JQuery?

How to extend Liferay 6.2 session timeout by AJAX call?