To remove elements from a List while iterating, you should use Iterator as shown below:
//set a reference to the list List<String> nameList = ..... //remove an element while iterating the list Iterator<String> iter = nameList.iterator(); while (iter.hasNext()) { String name = iter.next(); if (..condition here..) { // Remove the current element from the iterator and the list. iter.remove(); } }
You may also use a for-loop as shown below:
//set a reference to the list List<String> nameList = ..... //remove an element while iterating the list for (Iterator<String> iter = nameList.iterator(); iter.hasNext();) { String name = iter.next(); if (..condition here..) { // Remove the current element from the iterator and the list. iter.remove(); } }
You may also use a ListIterator by using the List's listIterator() method.
//set a reference to the list List<String> nameList = ..... //remove an element while iterating the list Iterator<String> iter = nameList.listIterator(); while (iter.hasNext()) { String name = iter.next(); if (..condition here..) { // Remove the current element from the iterator and the list. iter.remove(); } }
Note that Iterator.remove() and ListIterator.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.
Collection
Collection API
List API
No comments:
Post a Comment