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 ??
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 ??
There are 3 types of loops in Java. They do different things, and with regards to Collection
s, have different usage.
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 LinkedList
s, because get(i)
is O(n)
in those. It cannot be used with other Collection
s such as Set
s.
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 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.
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.
Best Way is Class Iterator
use to Iterate througout the Collection
but you have not mentioned Iterator
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.
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()
.
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.
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.