Hi all, I am new to Java Tech. My query is, I have one arraylist, I can iterate this arraylist with the help of for loop or by using Iterator(java.util package), but I want to know what is the best practice to do so, and which method is faster to iterate arralist or similar thing.
don't want to start a flamewar here, but i'd say that both techniques are equivalent.
obviously a for loop gives you the benefit of having a pointer / counter variable with you, while an iterator does not know very much about its position in the list.
since java 5 the for-each syntax allows the compiler to check type-consistency at compile time, but again, if you need the position in the list, you're better served with a for loop.
a word about performance:
from all my experience: "don't optimize pre-mature code". it's perfectly legal to ask yourself if the code is efficient, but the first goal while developing should always be functionality and maintainabilty. :-)
hope it helps, jan [ April 06, 2006: Message edited by: Jan Groth ]
My advice would be to change your point of view slightly, from "I have an ArrayList" to "I have a List" or even "I have a Collection" (Is the ordering in the List significant?). Perhaps you may decide to change to a LinkedList or a readonly wrapper on a list etc... Then, Iterator makes more sense, because the get() method can be expensive (O(N)) for LinkedLists. And as mentioned, the new syntax is cool:
The efficiency differences between an Iterator and using get() on an ArrayList are probably too slight to worry about, and then don't start tweaking your code until profiling leads you to this decision, which is unlikely...
Iterators are fail fast - any operation that structurally modifies the underlying collection( such as remove() ) will immediately have an affect on the iterator. However, looping over an index can have potential invalid references or skip elements if you remove() elements.
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Joined: Aug 25, 2005
Hi Jeff, I was talking about Collection and by ur answer got the idea abt the iterator and for loop. Thanx a lot.
Joined: Aug 25, 2005
Hi Ajith, Thanx for reply...one more thing...consider that I am using Collection objects, iterating the same without removing any elements from it. In such case which will be good option, for loop or Iterator?