Meaningless Drivel is fun!*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Fastest Way to traverse an ArrayList" Watch "Fastest Way to traverse an ArrayList" New topic
Author

Fastest Way to traverse an ArrayList

Karan Agnihotree
Greenhorn

Joined: Feb 26, 2008
Posts: 11
Hi
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?

Thanks
Ullas
James Elsey
Ranch Hand

Joined: Dec 21, 2007
Posts: 228

Use the for-each loop, such as :




prints


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
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Fastest Way to traverse an ArrayList
 
Similar Threads
Accessing ArrayList elements
Iterator vs for loop
Vector operation implementation why JDK preferred arrays over linkedlist
Vector vs Arraylist
html:select and html:options simple question