亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有一種算法可以圍繞 ArrayList 進行循環迭代?

有沒有一種算法可以圍繞 ArrayList 進行循環迭代?

拉風的咖菲貓 2023-10-13 09:58:32
也就是說,當我到達紙張末尾時,下一個元素為零。
查看完整描述

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;

    }

}


查看完整回答
反對 回復 2023-10-13
?
開滿天機

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);

}


查看完整回答
反對 回復 2023-10-13
?
萬千封印

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 …

}

等等...


可以設計方法來使用顯式迭代器而不是索引,但這完全取決于您想要實現的目標。


查看完整回答
反對 回復 2023-10-13
  • 3 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號