循环方式的java数组遍历

我有一个数组,其中包含1 2 3 4 5个值。

array a = [ 1 , 2, 3, 4, 5] 

现在我想以循环方式遍历它。 我喜欢打印2 3 4 5 1或3 4 5 1 2或5 1 2 3 4等等。 对此有何算法

编辑:我想以循环方式打印所有组合。 我不想在初始阶段说出起点。

 int start = ... for (int i = 0; i < a.length; i++) { System.out.println(a[(i + start) % a.length]); } 

我应该注意,就执行速度而言,这可能不是表达循环的最有效方式。 但是,差异很小, 很可能无关紧要

更相关的一点是,以这种方式使用%是否会提供更易读的代码。 我认为确实如此,但也许那是因为我之前看过/使用过这种特殊的习语。

以下怎么样:

 int start = // start position, must be in bounds int i = start; do { .... i++; if(i == a.length) i = 0; } while(i != start); 
 int st = n ; // n is the starting position from where you print for(int i = st; i < a.length; i++) { -- print each array[i]; } if(st != 0) { for(int i = 0 ; i < st ; i++) { --- print each array[i]; } } 

基本上你只需要循环遍历数组,并在必要时更改当前索引(比如在遇到结束时将其移动到数组的开头)

 public static void main(String[] args) { int[] array = new int[] { 1, 2, 3, 4, 5 }; System.out.println(printCircularly(array, 4)); } private static String printCircularly(int[] array, int startIndex) { StringBuilder sb = new StringBuilder(); int currentIndex = startIndex; do { sb.append(array[currentIndex++]); if (currentIndex > array.length - 1) { currentIndex = 0; } } while (currentIndex != startIndex); return sb.toString(); } 

除了斯蒂芬C的回答

 int start = ... for (int i = 0; i < a.length; i++) { System.out.println(a[(start - i + a.length) % a.length]); } 

从开始索引用于反向循环。 这有点不清楚,但在某些情况下非常有用。 例如:UI组件,如轮播。

并且没有ArrayIndexOutOfBoundsException !!!