• Post Reply Bookmark Topic Watch Topic
  • New Topic

Removing elements from list  RSS feed

 
Chandra shekar M
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have this code.


I think it should not behave like this?
>
 
Zandis Murāns
Ranch Hand
Posts: 174
Java Java ME Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Solution is to iterate backwards.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I re-formatted your code, and put in code tags. with over 100 posts, you've been around long enough to know how to do that yourself.

to your code...think about it. you set the size variable to 3.

you start iterating through, and remove an element. the lists size is now 2, but your size variable is still 3.

you move to the next element, and remove it. the list now has a size of 1. your counter is now set to 2, which is still less than your size variable, so we loop again.

you now say "remove the element at position 2", but the list only has one element in it - hence the out of bounds exception.
 
Chandra shekar M
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!