• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in arraylist  RSS feed

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have tried to iterate a list and if the object contains specific character i have to remove the object but it throws concurrentmodificationexception because iterate has been aware of what is modified.so i tried with for loop but its not working properly.



If i execute this objects in the list is not removed completely.I debugged the code the objects are swapped once its removed.


Please suggest me how to avoid concurrentmodificationexception
 
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the tutorial.

edit

the objects are swapped once its removed.


It should be rather obvious that if you remove, say, the second element, then the third element takes its place. To remove elements in a for loop, start at the highest numbered element and proceed toward zero.
 
Ranch Hand
Posts: 214
  • X Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Darryl Burke wrote:To remove elements in a for loop, start at the highest numbered element and proceed toward zero.



To remove objects from a list while iterating over it, using an iterator is the safer way I think. Something like:

 
Sheriff
Posts: 21182
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both techniques, using an Iterator or looping backwards, will solve this issue. Whichever you prefer is best -- I usually go for the Iterator.
 
syruss kumar
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the suggestion its helped me to resolve the issue .
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!