Forums Register Login

two ways of looping into a list

+Pie Number of slices to send: Send
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 ?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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:
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
 

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.
and POOF! You're gone! But look, this tiny ad is still here:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 915 times.
Similar Threads
remove the element in list while iterating through it.
Collection question
Error java util NoSuchElementException
NX: how to fill long[] results in findByCriteria()
Enhanced for loop and Iterator question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 05:45:30.