Erro com Collections: java.util.ConcurrentModificationException  XML
Índice dos Fóruns » Java Avançado
Autor Mensagem
oddy.silva
JavaEvangelist
[Avatar]

Membro desde: 24/11/2008 11:42:10
Mensagens: 352
Localização: Itu
Offline

Usando Iterator é a melhor forma:



Essa é a receita, igual o amigo acima falou.

Odair
Gestão em T.I
FATEC - ITU
"Quem quer fazer alguma coisa, encontra um meio"

Quer ser um programador veloz? Então compre um par de tênis a jato.
[Email]
FrancoC
JavaTeenager
[Avatar]

Membro desde: 15/10/2009 13:11:25
Mensagens: 193
Offline

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:






Get the facts first. You can distort them later.
eu06egv
Smalltalk

Membro desde: 28/12/2007 19:03:43
Mensagens: 1
Offline

Ola, eu tive o mesmo problema e resolvi da seguinte maneira, eu encapsulei a minha Collection a ser acessada pelas demais Threads e
sincronizei os metodos get e set de acesso, logo todos que precisam acessar a Collection, acessam pelo get ou set entao isso nao da
java.util.ConcurrentModificationException, no meu caso funcionou muito bem.

Espero q eu tenha ajudado

HarleySeixas
HelloWorld

Membro desde: 25/10/2006 00:04:57
Mensagens: 12
Offline

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:









Perfeito, sua solução resolveu o meu problema. Valeu!!!!!!

This message was edited 2 times. Last update was at 15/09/2010 01:58:48

fmarinzeck
Smalltalk
[Avatar]

Membro desde: 06/08/2011 07:29:18
Mensagens: 4
Localização: Maringá - PR
Offline

Opa...

Seu --i também solucionou meu problema!

Valeuu...

It's Only Business.
clebiovieira
JavaChild
[Avatar]

Membro desde: 07/09/2009 22:53:56
Mensagens: 101
Localização: Rio de Janeiro
Offline

danilloh wrote:Mais uma opção...






Funcionou delicia !!! Parabéns.. Achei essa aqui mais elegante. abs...






[WWW] [MSN]
 
Índice dos Fóruns » Java Avançado
Ir para:   
Powered by JForum 2.1.8 © JForum Team