3 回答

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
嘗試這個(gè):
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貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
就在這里:
考慮以下代碼:
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貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
鑒于您已經(jīng)聲明并填充了ArrayList我將調(diào)用的list,那么您只需對(duì)列表大小取模即可進(jìn)行迭代。具體如何寫取決于您想要做什么。
1)一直循環(huán)下去:
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) 精確地循環(huán)列表一次,但從某個(gè)任意點(diǎn)開始base:
for (int offset = 0; offset < list.size(); offset++) {
int index = (base + offset) % list.size();
value = list.get(index);
… process value here …
}
等等...
可以設(shè)計(jì)方法來使用顯式迭代器而不是索引,但這完全取決于您想要實(shí)現(xiàn)的目標(biāo)。
添加回答
舉報(bào)