dcsimg
Iterator or traversing using an index
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Safder_Meah
Posted On:   Tuesday, July 25, 2006 03:13 PM

Hi everyone,

I had a question regarding iterating through an array list.
I understand that the norm, is to use an Iterator to iterate through a list. However if I use something similar to the following code:


			
for(int i = 0; i < arrayList.size();i++){
int x = arrayList.get(i);
}


Is the above code a "bad" way of iterating. If it is, can someone tell me why? Also which is better in terms of performance assuming that we need to go through the list only once...forward. Thank you

Re: Iterator or traversing using an index

Posted By:   Anonymous  
Posted On:   Thursday, August 3, 2006 10:25 AM

Short answer:

Use an iterator in the above example since that's what they're for.


Longer answer:

Using an iterator makes no assumption on the random-accessibility of your collection. Therefore you could replace the list in your code by another random Collection without a sweat.

Also, although the performance of an ArrayList is pretty good for random-access (get(i)), for a LinkedList, the get(i) method becomes relatively expensive.


One more thing: if you know the size doesn't in the middle of your iteration, it is not advised to re-call size() in each iteration! Iterators throw appropriate exceptions for concurrent modifications as well.

Re: Iterator or traversing using an index

Posted By:   Daniel_Camacho  
Posted On:   Thursday, July 27, 2006 09:38 AM

I use:

Iterator it = Collection.iterator();

while(it.hasNext()){

}



dont askme which is better...

Re: Iterator or traversing using an index

Posted By:   Anonymous  
Posted On:   Tuesday, July 25, 2006 08:03 PM

Yes because you are forcing the arrayList.get() to re-evaluation from index 0 thru to index "i" for each iteration.



This may not have a big impact with small arrays but for large arrays you are foring it to skip records every time, rather than work from the position you got to last time.



The Iterator interface and #iterator() method are designed to address exactly this problem.
About | Sitemap | Contact