我想了解循环列表的逻辑。当我到达列表末尾时,我希望索引再次从 0 开始。该列表在循环中运行,并且会发生终止,因此不会是无限循环。
我已经看到使用 % 运算符的解决方案,但我不明白它。类似于下面的内容,但用 % 代替。我想了解它是如何工作的。
for(int i = 0; i < n; i++) {
if(i == n - 1) { i = 0; }
}
最佳答案
modulo operator %
是除法后的余数。
Given two positive numbers, a and n, a % n is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
你说你有一个列表,如果你使用% list.length()
,这将为你提供从0到list.length()的值。
请参阅以下代码:
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
for (int i = 0; i < 10; i++) {
System.out.println("element: " + list.get(i % list.size()));
}
此输出:
element: first
element: second
element: third
element: first
element: second
element: third
element: first
element: second
element: third
element: first
您可以检查它是否正常工作 here .
关于java - 循环遍历列表 - 当索引到达末尾时,从 0 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61000980/