有没有一种算法可以围绕 ArrayList 进行循环迭代?

也就是说,当我到达纸张末尾时,下一个元素为零。



拉风的咖菲猫
浏览 125回答 3
3回答

缥缈止盈

尝试这个:ArrayList<Object> list = new ArrayList<>(); // + add some values to the listfor (int i = 0; i < list.size(); i++) {&nbsp; &nbsp; someMethod();&nbsp; &nbsp; if (some condition) {&nbsp; &nbsp; &nbsp; &nbsp; break; // you need to add some break condition, otherwise, this will be an infinite loop&nbsp; &nbsp; }&nbsp; &nbsp; if (i == list.size() - 1) {&nbsp; &nbsp; &nbsp; &nbsp; i = -1;&nbsp; &nbsp; }}

开满天机

就在这里:考虑以下代码:for (int i = 0; i < 100; i++) {&nbsp; &nbsp;// Output will be: 0,1,2,3,4,5,6,7;0,1,2,3,4,5,6,7;...&nbsp; &nbsp;System.out.println(i % 8);}

万千封印

鉴于您已经声明并填充了ArrayList我将调用的list,那么您只需对列表大小取模即可进行迭代。具体如何写取决于您想要做什么。1)一直循环下去:int index = 0;while (true) {&nbsp; &nbsp; value = list.get(index);&nbsp; &nbsp; … process value here …&nbsp; &nbsp; index = (index + 1) % list.size();&nbsp; &nbsp; // or equivalently to previous line: if (++index >= list.size) index = 0;}2) 精确地循环列表一次,但从某个任意点开始base:for (int offset = 0; offset < list.size(); offset++) {&nbsp; &nbsp; int index = (base + offset) % list.size();&nbsp; &nbsp; value = list.get(index);&nbsp; &nbsp; … process value here …}等等...可以设计方法来使用显式迭代器而不是索引,但这完全取决于您想要实现的目标。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java