Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why to use iteration instead of size for list?  RSS feed

 
par dhar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Sorry to ask such a basic queation, but can anybody please let me know why it is adviced to use iteration to loop thro' list elements instead of size() method?

Regards
Parag
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16027
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To clarify your question, here's a piece of code:

The answer is this: There are different implementations of interface List, for example ArrayList and LinkedList. The main difference between these implementations is that for one, some operations are efficient and other operations are less efficient and vice versa.

For example, random lookup (using get(...)) is efficient on an ArrayList, but not on a LinkedList (because it has to walk through the whole list to get at the element you are looking for). So the second loop (using "size()") is very inefficient when the List is a LinkedList.

Using an iterator is better, because the iterator that you get from the list "knows" what the most efficient way is for looping through the list. (The list itself supplies the iterator, so it can give you an iterator that is efficient for that particular implementation of List).
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, by using an iterator, you are using the same interface for every kind of list. I can always use the same code, no matter what kind of implementation the unerlying list has.

there are cases where i don't care what the underlying implementation is - i just want a list. i want to be able to loop over it.

if i do it your way, i am locking myself into a specific algorithm. if the list changes how it's designed, or somebody come up with a brand new kind of list, you might be out of luck until you can re-factor your code to handle the changes.

using an iterator, i have a common way to go through ANY kind of list, as long as that list supports the iterator interface. maybe we have 12 different lists we need to iterate through, one an array list, one a map, one a set... i can write



you would have to write:



my code lets anybody add any new kind of list any time they want, or change the underlying implementation of an existing list, and i don't care. my code doesn't break.

yours can't handle a new type of list without you changing your code. and if somebody changes how an existing list works, you might be out of luck again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!