你能重置 for-each 循环的计数器吗?

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

因为那里没有可访问的计数器或 i 可以重置为零。

有什么办法可以通过 continuebreak 来实现吗?

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

不,for each 循环内部不使用任何计数器。因此,只需使用像这样的常规循环:

for (int i = 0; i < myCollection.size(); i ++) {
    // do something
}

更多信息:Is there a way to access an iteration-counter in Java's for-each loop?

通常,没有办法做到这一点:用于 "drive" for-each 循环的迭代器是隐藏的,因此您的代码无法访问它。

当然,您可以创建一个类似集合的 class,它保留对其创建的所有迭代器的引用,并允许您进行重置 "on the side"。但是,这属于 hack,应该避免。

如果您需要一种方法将迭代的位置重置回特定位置,请使用常规 for 循环。