Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in arraylist

 
syruss kumar
Ranch Hand
Posts: 107
  • 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
 
Darryl Burke
Bartender
Posts: 5149
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.
 
D. Ogranos
Ranch Hand
Posts: 214
  • 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:

 
Rob Spoor
Sheriff
Pie
Posts: 20744
68
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: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the suggestion its helped me to resolve the issue .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic