No, but you can provide your own counter.
The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).
No, but you can provide your own counter.
The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).
There is another way.
Given that you write your own Index class and a static method that returns an Iterable over instances of this class you can
for (Index<String> each: With.index(stringArray)) {
each.value;
each.index;
...
}
Where the implementation of With.index is something like
class With {
public static <T> Iterable<Index<T>> index(final T[] array) {
return new Iterable<Index<T>>() {
public Iterator<Index<T>> iterator() {
return new Iterator<Index<T>>() {
index = 0;
public boolean hasNext() { return index < array.size }
public Index<T> next() { return new Index(array[index], index++); }
...
}
}
}
}
}
[Java] Simple explanation of for each loops
How to access c:forEach index from the tag - Oracle Forums
How to get an index for current iteration of For Each
How to add index for each record in an array of objects
Videos
You can't, you either need to keep the index separately:
Copyint index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}
or use a normal for loop:
Copyfor(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}
The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"
Keep track of your index: That's how it is done in Java:
Copyint index = 0;
for (Element song: question){
// Do whatever
index++;
}
Hi, every example I see of for each loops I see confuses me. I know for for loops it is: for(begining counter; do while counter is less, greater or equal to n; increase or decrease counter) . I was hoping someone could help explain how for each loops work and there applications instead of for loops. Sorry if this is a basic question, other answers I found in the java documentation and on stackoverflow didn't seem to help me.
Edit: I understand now! Thank you guys so much!