Reputation: 21
Please tell me the difference between for loop and iterate? when should i use for/iterate?
ex:-
for(int i=0;i<arrayList.size();i++)
{
System.out.println(arrayList.get(i));
}
// using iterator
Iterator animalItr = animalList.iterator();
while(animalItr.hasNext()) {
String animalObj = (String)animalItr.next();
System.out.println(animalObj);
}
Upvotes: 1
Views: 144
Reputation: 159754
Using an Iterator to iterate through a Collection is the safest and fastest way to traverse through a Collection.
For the collections like ArrayList here, which are array-backed, it might not make a difference.
One of the best reasons for using an Iterator is that you can safely modify the collection without raising a ConcurrentModificationException.
Upvotes: 0
Reputation: 476990
Looping via iterators is more general than via indices. Iterators can be used to iterate over any collection. By contrast, a positional index is a technical detail of sequence containers. The only reason you might want to be this particular is if the sequential nature of the container is intrinsic to your problem and you need to know the numeric position for your algorithm.
But otherwise, and in general, you should prefer the iterator style, because it is more general and will thus lead to more uniform code. Different parts of your code may use different containers (or you may even wish to change the container later), but you will immediately recognize iterations if you write all of them in the same way, rather than having a different style depending on the details of the container.
That said, it is even more preferable to use a range-based for
loop whenever you only want to act on each element in the container, without wanting to modify the entire container as a whole (via insert/delete). When you say for (String s : arrayList) { /*...*/ }
, you don't even need to mention the name of the container or of any iterator in the body of the loop! With this in mind, iterator (or index) loops should be reserved for situations where you decide inside the loop that you need to modify the container, e.g. by erasing the current element, or where the position of the element inside the container is relevant.
Upvotes: 4
Reputation: 6992
When it gets to Iterable
objects, I'd personally use a for-each loop:
for(Type t : iterableObject) {
//body
}
Upvotes: 0