2

What criteria should be met when deciding which of the following loops to use to iterate over elements in a collection. For example in what context will one loop be more efficient than another?

  • For Loop ??
  • While Loop ??
  • For-Each Loop ??
DJG
  • 61
  • 1
  • 1
  • 5
  • 1
    I vote on `do-whlie loop`, becuse it's my favorite loop. The question is opionon based, and I vote to close it. – krokodilko May 06 '16 at 18:04
  • 1
    @kordirko it is not opinion-based. The OP is not asking for your opinion, but for the features and benefits of each type of loop, for their possible use cases. – njzk2 May 06 '16 at 18:14
  • They are all the same pick you favorite and delete the question – joe pelletier May 06 '16 at 18:19

4 Answers4

4

There are 3 types of loops in Java. They do different things, and with regards to Collections, have different usage.

Traditional For loop

The traditional for loop looks like:

for (int i = 0; i < list.length(); i++) {
    Object o = list.get(i);
}

It is useful when you need to use the index for something else than accessing the element, like when you have 2 loops, or when you affect the index to some value in the object.

It can be used only with lists, and even then, should never be used with LinkedLists, because get(i) is O(n) in those. It cannot be used with other Collections such as Sets.

The same syntax can also be used on arrays (use length field instead of the length() method), or on Strings (using size() and charAt)

It is usually not the best loop. It does not prevent you from messing with the i variable, or with the content of the list, which can lead to surprising results.

While loop

While loop can be used for a lot of things, but in the case of a Collection, it is used when you need to remove elements from a list. It requires an Iterator, which is a little more work:

Iterator<String> iter = coll.iterator();
while (iter.hasNext()) {
    String elem = iter.next();
    iter.remove();
}

It allows you to safely delete any element of the collection. It works on any Collection (List or Set).

It does not give you direct access to the index, but Collection and Iterable know nothing about indexed access anyway.

Fast-enum for loop

The latest addition is a short version of the above, without the possibility of removing items:

for (String elem : coll) {

}

It is the clearest. It does not involve any extra variable and works on any Iterable, as well as on arrays.

You are forbidden from modifying the collection(it will throw a ConcurrentModificationException) when looping (from inside the loop or from another thread), which guarantees the consistency of the data.

Use it whenever possible.

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • Actually for performance reason, the best way to loop over a list is this: for (int i = 0,length = list.length(); i < length; i++) – Nicolas Filotto May 06 '16 at 18:22
  • 1
    @NicolasFilotto I would argue that no: https://stackoverflow.com/questions/256859/is-there-a-performance-difference-between-a-for-loop-and-a-for-each-loop – njzk2 May 06 '16 at 18:47
  • well it is not what JProfiler told me hundreds of times on code where we iterate over an ArrayList but ok if you say so – Nicolas Filotto May 06 '16 at 18:50
  • I guess that if god Bloch said so, I'm probably wrong but anyway I only trust what I can see :-) – Nicolas Filotto May 06 '16 at 18:52
  • I tend to trust that guy more that you, for some reason. – njzk2 May 06 '16 at 19:45
  • Don't you agree that a for-each loop creates behind the scene an iterator ? And creating an object has a cost, right? when you iterate using index like we do in case of a List, we don't create any objects so why it would be slower? Moreover using a variable length to store the length also allow to avoid checking the size at each call. Finally I've just re-read the item 46 of Bloch, it is global point of view about how to iterate over collections, here I'm talking of specific cases, I'm talking about the List only. – Nicolas Filotto May 06 '16 at 20:50
  • `List` does not guarantee you the complexity of `get(index)` – njzk2 May 06 '16 at 22:32
  • 1
    Good point, this optimization only works for ArrayList then – Nicolas Filotto May 07 '16 at 08:48
2

Best Way is Class Iterator use to Iterate througout the Collection but you have not mentioned Iterator

  1. I will recommend foreach loop. because in for or while or do-while there is need of defining external Counters to get end of the loop condition. but in for-each there is no need of external Variables.

  2. IndexOutOfBoundException :- It will not raise in for-each but if we type any logical mistake then other may raise this exception (in context of Array).

but if your need to play with the index then you should use for or do-while() or while().

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
1

First use a for-each loop when it is appropriate: iterating over the whole collection and only needing the elements (not their index).

If for-each is not appropriate then choose for-vs.-while based on whether you reasonably need the 3 parts of a for-loop, ie. use while if you would only use the condition/middle part of a for-loop.

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
0

If the collection is arraylist here are the three choices available :

array index loop:

for (int i = 0; i < collection.length; i++) {
        type array_element = collection.get(index);

    }

the Iterator hasNext()/next():

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
    type type = (type) iterator.next();

}

simplest :

for (iterable_type iterable_element : collection) {

}

The first one is useful when you need the index of the element as well.

The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate.

The third version is simple and preferred by all. It is short and works for all cases where you do not need any indexes or the underlying iterator.

PeaceIsPearl
  • 329
  • 2
  • 6
  • 19