I know that currently there are two approaches to loop over an List
. But let's complicate it a bit more, consider:
- You iterate over
List<E> list
. - You want to keep track of an
int y
on every iteration. - There exists a function
process(E elem, int y)
that processes an item.
Option 1:
for (int i = 0, y = 0; i < list.size(); i++, y++) {
process(list.get(i), y);
}
which actually just is
for (int i = 0; i < list.size(); i++) {
process(list.get(i), i);
}
Option 2:
int y = 0;
for (E elem : list) {
process(elem, y);
y++;
}
which can be rewritten to
int y = 0;
for (E elem : list) {
process(elem, y++);
}
However why does the following not exist? What are the objections to it not existing?
Option 3:
for (int y = 0; E elem : list; y++) {
process(elem, y);
}
Two arguments to have this construct:
- Both
foreach
syntaxes are distinguishable - Many objects implement
Iterable<E>
, but have nofor
counterpart. This happens when anIterable<E>
has no order associated with it for example.