3 回答

TA貢獻2041條經驗 獲得超4個贊
嘗試這個:
ArrayList<Object> list = new ArrayList<>(); // + add some values to the list
for (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;
}
}

TA貢獻1786條經驗 獲得超13個贊
就在這里:
考慮以下代碼:
for (int i = 0; i < 100; i++) {
// Output will be: 0,1,2,3,4,5,6,7;0,1,2,3,4,5,6,7;...
System.out.println(i % 8);
}

TA貢獻1891條經驗 獲得超3個贊
鑒于您已經聲明并填充了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 …
}
等等...
可以設計方法來使用顯式迭代器而不是索引,但這完全取決于您想要實現的目標。
添加回答
舉報