Posts

Showing posts with the label Iterator

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....