1

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);
}
2
  • Well one thing to keep in mind is that sometimes you have to use an iterator. Commented Sep 8, 2012 at 11:44
  • FWIW, the enhanced for loop is comfortable to iterate through collections unless it is really necessary to know the position. Commented Sep 8, 2012 at 11:45

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

When it gets to Iterable objects, I'd personally use a for-each loop:

for(Type t : iterableObject) {
 //body
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.