尝试这个:ArrayList<Object> list = new ArrayList<>(); // + add some values to the listfor (int i = 0; i < list.size(); i++) { someMethod(); if (some condition) { break; // you need to add some break condition, otherwise, this will be an infinite loop } if (i == list.size() - 1) { i = -1; }}
鉴于您已经声明并填充了ArrayList我将调用的list,那么您只需对列表大小取模即可进行迭代。具体如何写取决于您想要做什么。1)一直循环下去:int index = 0;while (true) { value = list.get(index); … process value here … index = (index + 1) % list.size(); // or equivalently to previous line: if (++index >= list.size) index = 0;}2) 精确地循环列表一次,但从某个任意点开始base:for (int offset = 0; offset < list.size(); offset++) { int index = (base + offset) % list.size(); value = list.get(index); … process value here …}等等...可以设计方法来使用显式迭代器而不是索引,但这完全取决于您想要实现的目标。