Alguem pode me explicar esse codigo... java.util.ConcurrentModificationException

3 respostas
J
public class Question {
	public static void main(String argv[]) {
		List a = new ArrayList();
		a.add("a1");
		a.add("a2");
		a.add("a3");

		Iterator it = a.iterator();

		while (it.hasNext()) {
			if (it.next().equals("a1")) {
				a.remove("a1");
			}
		}
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

estava fazendo um simulado aqui e vi essa questão que ate agora não consegui entender....

3 Respostas

nbluis

jc.thalys:
while (it.hasNext()) { if (it.next().equals("a1")) { a.remove("a1"); } }

Aqui vc está no meio de uma iteração da lista, não pode remover itens dela ao mesmo tempo.

para isso não poderá utilizar o iterator.

Mantu

Sempre que você tenta modificar um List enquanto está iterando um Iterator, você terá essa exceção. De uma lida na API da interface List e da Iterator

maquiavelbona

Javadoc é meu salvador e nada me faltarás.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/ConcurrentModificationException.html

Javadoc:
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it…

Com um pouco de inglês, não precisa de explicação.

Até!

Criado 16 de julho de 2007
Ultima resposta 16 de jul. de 2007
Respostas 3
Participantes 4