• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Iterator.remove()

 
Haakon Lind
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When running this shuffler program I expect to get five random objects and then a null at the end. But I`m getting six objects in output when I got 5 declared. I think it`s because I don`t know how to use the Iterator.remove() method properly.
Here`s the code:

PS! the two calls to hand[3] is always the same.
Thanks for any help!
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Haakon,
The iterator is working fine. The problem is that hand[3] still holds the value from the previous assignment. Try using hand[size + 3] in the second loop and dump hand[4], hand[5] and hand[6] instead and see what happens.
Michael Morris
 
Haakon Lind
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Michael, didn`t see that it couldn`t cast a null as it skips the last code on hand[3] and thus the old object is still in place.
Got a ....OutOfBoundsException when i tried your tip, but I threw in this at the end instead:

So now it works
Thanks again,
Haakon
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Got a ....OutOfBoundsException when i tried your tip, but I threw in this at the end instead:

That's why I told you to do it that way so you could see what was going on, ie that the second loop only had two iterations, otherwise the Exception would have occurred in the loop instead of the Sysout.
Michael Morr
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic