• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing ArrayList elements

 
KasiMurugan Ramasamy
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Friends,

we can access arrayList's elements using
1. get(index)
2. using Iterator

Which one gives better performance.
 
Jan Groth
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"don't guess - measure"
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an advanced question. Moving...
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by KasiMurugan Ramasamy:
Which one gives better performance.


Are you regularly working through many millions of entries? Because, if not, this question is unlikely to be worth considering. Both methods will be really fast, and their execution time will be swamped by that of whatever else you're doing in the loop.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The more important question is for the List interface in general, which one is likely to be faster? For if today you're using an ArrayList, the same code may be used with a LinkedList tomorrow. Whereas for ArrayList there is virtually no difference between get() and iterator().next(), for LinkedList there's a big difference: an Iterator is faster by a mile. As a rule, use Iterators, because the Iterator for any given List implementation will be designed to access that list in the most appropriate (i.e., fastest) way possible.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I was replying to a specific question about ArrayList. For ArrayList, there is a tiny difference between the two.

If you've got a List, which could be implemented any way, I agree that Iterator is definitely best.

What about Java 5+ enhanced "for" loop? That uses Iterator, I suppose?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
That uses Iterator, I suppose?


Yes. There's a new "Iterable" interface; anything that implements Iterable can be used with that loop. I believe "iterator()" is the only method in the interface.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!