Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

two ways of looping into a list

 
Kaylee Sebi
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I want to loop through an ArrayList aList, instead doing the following:

Itereator it= aList.iterator();
while ( it.hasNext() ){...}

Another way is:

for(Iterator ii = aList.iterator(); ii.hasNext(); ){...}

What is happening under the scene in these two scenarios ?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best way to find out is to use javap to take a look at the byte code for both loops.

My guess would be that they are (near to) identical.
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was taught that the "correct" way to iterate an ArrayList is to use an Iterator, rather than a "for" loop with a counter. But recently I came across the RandomAccess tagging interface; it suggests that a for loop with a counter may be faster for an ArrayList. Have a look at the API docs for ArrayList and RandomAccess.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither of the examples that Kaylee shows involves a for-loop with a counter.

If you are using Java 5 or newer and you don't need explicit access to the iterator, then the shortest and clearest way to iterate over a list is to use the new "for each" syntax:
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a Java 1.3 and 1.4 environment at work, I've recently started using Keylee's 2nd example style with a for loop and an iterator. I resisted for a while because I thought for loops so often used an int counter or index that it might confuse readers to do something else. I guess getting rid of a line of code and a variable scoped outside the loop finally won me over.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper Young:

If you are using Java 5 or newer and you don't need explicit access to the iterator, then the shortest and clearest way to iterate over a list is to use the new "for each" syntax


True - it will be the shortest and clearest source code, which is important. I'd again guess that the compiled byte code will be still near to identical.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic