Win a copy of Java Challengers this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

Removing Items from an Iterated ArrayList

 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When I try using the remove method of an iterator, it will instead create a duplicate of the next element in the ArrayList.

For example if I have my ArrayList with:
Object A
Object B

and I while the iterator is on Object A, and I use it.remove() I end up with and ArrayList of:
Object B
Object B

Obviously this is not what I want.
Code as follows...

 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


and I while the iterator is on Object A, and I use it.remove() I end up with and ArrayList of:
Object B
Object B


How did you verify this? Did you put something like the following directly after the while loop?



I see some strange things in the code:

Did you deliberately print out the same object each time (get(0))?



This means that in the [A, B] list case, B will be processed inside the while loop and once again in this if statments after the while loop?

To be correct, the behaviour of the remove() method depends on the implementation of the Iterator (and possibly the behaviour of the underlying List), but if it is really an ArrayList, it should give you the expected behaviour.
 
Atrus Greyor
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, wow, missing that made me feel a little bit slow.

Yeah, that was my problem, and it really is working as was intended.

Thanks for the help.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic