• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

index access Vs iterator access

 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ranchers ,

index access Vs iterator access : which one is fast ?

as in my view index access is fast since it provide direct access to collection elements As for iterator provides sequential access .

share your opinion.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That depends on the data structure.

Arrays and ArrayList provide efficient random access, which means that you can quickly lookup an element by index. But LinkedList does not provide efficient random access; to find the element at a specific index in a LinkedList, the program must walk over all elements in the list until the required element.

If you're just looping through the elements of an array or ArrayList, then it does not really matter if you do it by index or via an iterator; both will be approximately equally fast.

If you're looping through the elements of a LinkedList, then doing it via an index will be slower than using an iterator, because for every element the program will have to walk trough the list to find the element at the specified index.
 
Winston Gutkowski
Bartender
Pie
Posts: 10268
60
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:If you're just looping through the elements of an array or ArrayList, then it does not really matter if you do it by index or via an iterator; both will be approximately equally fast.
If you're looping through the elements of a LinkedList, then doing it via an index will be slower than using an iterator...

All of which means that if you're looping through the elements of a List (ie, you don't know what the implementation is), you should generally use an Iterator.

And just to add to what Jesper said: Lists that have good random-access performance are supposed to implement java.util.RandomAccess, which you can check for with instanceof.
All the Lists in the standard libraries follow this rule; but there may be 3rd-party ones that don't.

Winston
 
Stephan van Hulst
Bartender
Pie
Posts: 5590
55
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On a related note, prefer the enhanced for loop to the regular one.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan is right, and the enhanced for loop syntax will make use of an Iterator below the covers, so that it's efficient for both ArrayList and LinkedList.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic