James
James

Reputation: 99

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

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

Upvotes: 7

Views: 3855

Answers (2)

flogy
flogy

Reputation: 937

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?

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

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.

Upvotes: 3

Related Questions