• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fastest Way to traverse an ArrayList

 
Karan Agnihotree
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 228
Android IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic