我正在使用 Iteratot 迭代 ArrayList 的元素。在迭代时,我在最后将一个元素添加到 ArrayList 中。但是得到一个错误:ConcurrentModificationException。
如果我将 ArrayList 更改为 Set 并尝试在迭代过程中最后在 set 中添加元素,则不会抛出错误
测试.java
class Test {
public static void main() {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(20);
al.add(30);
al.add(40);
Iterator<Integer> it = marks.iterator();
while (it.hasNext()) {
int value = it.next();
if (value == 40) al.add(50);
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试2.java
class Test2 {
public static void main() {
Set<Integer> marks = new HashSet<>();
marks.add(20);
marks.add(30);
marks.add(40);
Iterator<Integer> it = marks.iterator();
while (it.hasNext()) {
int value = it.next();
if (value == 40) marks.add(50);
}
}
}
Run Code Online (Sandbox Code Playgroud)
可能有更好的解决方案,但这个解决方案也有效。在循环完成后,使用第二个列表,然后将其添加到原始列表中。
主要的
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> al = new ArrayList<Integer>();
List<Integer> toAdd = new ArrayList<Integer>();
int stepSize = 10;
al.add(20);
al.add(30);
al.add(40);
Iterator<Integer> it = al.iterator();
while (it.hasNext()) {
int value = it.next();
if (value == al.get(al.size() - 1)){
toAdd.add(value + stepSize);
}
}
// Add all elements
al.addAll(toAdd);
// Print
al.forEach(System.out::println);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想根据最后一个值附加一个元素,如您的示例所示,您也可以等到循环完成(如果您仍然需要它)并尝试像这样添加它:
al.add(al.get(al.size() - 1) + stepSize);
Run Code Online (Sandbox Code Playgroud)
输出
20
30
40
50
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4350 次 |
| 最近记录: |