File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Fastest Way to traverse an ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Fastest Way to traverse an ArrayList" Watch "Fastest Way to traverse an ArrayList" New topic

Fastest Way to traverse an ArrayList

Karan Agnihotree

Joined: Feb 26, 2008
Posts: 11
Can any one please tell me which is the fastest way to traverse a arrayList. a For loop or a iterator? Which one should be prefered to be used in the code?

James Elsey
Ranch Hand

Joined: Dec 21, 2007
Posts: 228

Use the for-each loop, such as :


The for-each loop means "for each String in myStrings, assign it to s, do whatever is in the code block, then look at the next String in myStrings, assign it to s and do the code block, keep doing for each occurence of a String"

Kind Regards, James. OCPJP 1.6 || My SCJP / OCJCP Study Notes
Interested in : SCJP, Google App Engine, Stripes, Android;|| My Bite-Size SCJP Study Blog
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Actually, the proper answer is "it depends". For ArrayList, the fastest way would be to use size() and get(int). For LinkedList, the fastest way would be to use an Iterator. The difference can be found out by checking if the List implements RandomAccess:
However, this kind of optimization is hardly ever needed. The difference in both speed and memory for ArrayList is hardly noticeable. I suggest you follow James' advice, and use the for-each loop. It's easier to write, easier to read, and it allows Oracle (or any other compiler developer) to make the choice for you. Although usually for-each loops are transformed into my Iterator loops, technically this doesn't have to occur. I don't think there is a requirement to write a for-each loop using an Iterator. It's easier to do so, not having to make any distinction, but they both would result in similar code.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Fastest Way to traverse an ArrayList
It's not a secret anymore!