• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reusing Iterator reference  RSS feed

 
Rafael Andrade
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. My question is:
is there any problem in reusing the iterator reference?
like this:

Iterator it = list1.iterator();
while (it.hasNext()){ .......}

it = list2.iterator();
while (it.hasnext()){ .......}

or is it better to do this way, declaring another variable?

Iterator it = list1.iterator();
while (it.hasNext()){ .......}

Iterator it2 = list2.iterator();
while (it2.hasnext()){ .......}

thanks!!!
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hazardous. It is probably best always to declare Iterators as local variables. This is because they throw an Exception (I think it's called ConcurrentModificationException) if any members of their parent collection are added, removed, or rearranged.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally I found problems in both.

I only ever use them in for-loops to reduce the scope and take care when nesting or exposing them.

eg


When I code, trying to give them new names as in your second case tends promote copy-and-paste errors, while the first case means it isn't always clear what the variable is referring to.
[ April 23, 2007: Message edited by: David O'Meara ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From a pure technical point of view, though, there is no problem with reusing the reference.
 
Rafael Andrade
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice, thanks, guys!
From now on, I�ll only iterate inside a for loop.

Cya.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!