Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you reset the counter of a for-each Loop?

Tags:

java

foreach

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
like image 957
James Avatar asked Mar 23 '15 20:03

James


2 Answers

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.

like image 81
Sergey Kalinichenko Avatar answered Nov 11 '22 17:11

Sergey Kalinichenko


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?

like image 43
flogy Avatar answered Nov 11 '22 17:11

flogy