java - 循环遍历列表 - 当索引到达末尾时,从 0 开始

标签 java arrays list loops

我想了解循环列表的逻辑。当我到达列表末尾时,我希望索引再次从 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/

相关文章:

java - 以编程方式向 ShapeDrawable 添加阴影

java - java中检查文件是否存在的最快方法

c - 多维数组越界访问

python - 创建不是同一个列表的空白列表的字典

java - 在运行时更改 JComboBox 的内容

java.lang.ClassCastException : android. 小部件.TextView。为什么我会得到这个?

java - 找出数组是否包含唯一元素

javascript - javascript数组indexOf中使用的正则表达式

c# - 在 C#.net 中将 List<DataRow> 转换为 List<UserEntity>

c# - 使用后期绑定(bind)获取 List<T> 值