FrancoC wrote:
oddy.silva wrote:Usando Iterator é a melhor forma:
Essa é a receita, igual o amigo acima falou.
Há um problema nesse código que ainda pode disparar a ConcurrentModificationException
Segunda a Sun a interface java.util.Iterator define:
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
* Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
* Method names have been improved.
Ou seja ele foi especialmente criado para permitir a remoção de elementos de uma coleção durante uma iteração além das outras duas funcionalidades de verificacao e busca do proximo elemento que já eram providas pela interface Enumeration, porém no Iterator com nomes mais simples.
No seu código voce não remove o elemento da lista através do método remove() do Iterator.
Os três métodos do Iterator:
boolean hasNext() : Returns true if the iteration has more elements.
Object next() : Returns the next element in the iteration.
void remove() : Removes from the underlying collection the last element returned by the iterator (optional operation).
Descrição do método remove:
public void remove()
Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Throws:
UnsupportedOperationException - if the remove operation is not supported by this Iterator.
IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.
O código correto ficaria assim: