since there's no accessible counter or i
in there to reset to zero.
is there any way to play around with continue
or break
to achieve that?
class CommandLine {
public int[] sort(int array[]) {
int temp;
for (int i=0; i<array.length-1; i++) {//must have used for-each
if (array[i] > array[i+1]){
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
i=-1;
}//if end
}//for end
return array;
}//main end
}//class end
Generally, there is no way of doing this: the iterator that is used to "drive" the for-each
loop is hidden, so your code has no access to it.
Of course you could create a collection-like class that keeps references to all iterators that it creates, and lets you do a reset "on the side". However, this qualifies as a hack, and should be avoided.
If you need a way to reset the position of your iteration back to a specific location, use a regular for
loop.
No, the for each loop internally does not use any counter. Therefore, just use an usual loop like:
for (int i = 0; i < myCollection.size(); i ++) {
// do something
}
More information: Is there a way to access an iteration-counter in Java's for-each loop?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With