我有一个带有自定义列表类的应用程序。当尝试使用客户参数执行 foreach 函数时,会发生以下情况:
重要的!我无法修改 main 中的代码
主要的:
XList<Integer> lmod = XList.of(1,2,8, 10, 11, 30, 3, 4);
lmod.forEachWithIndex( (e, i) -> lmod.set(i, e*2));
System.out.println(lmod);
lmod.forEachWithIndex( (e, i) -> { if (i % 2 == 0) lmod.remove(e); } );
System.out.println(lmod);
lmod.forEachWithIndex( (e, i) -> { if (i % 2 == 0) lmod.remove(i); } );
System.out.println(lmod);
XList 类:
public class XList <T> extends ArrayList<T> {
public XList(Collection<T> collection) {
super(collection);
}
public XList(T... ints) {
super(Arrays.asList(ints));
}
public static <T> XList<T> of(Set<T> set) {
return new XList<>(set);
}
public static <T> XList<T> of(T... ints) {
return new XList<>(ints);
}
public void forEachWithIndex(BiConsumer<? super T, ? super Integer> consumer) {
Iterator<T> iterator = this.iterator();
int counter = 0;
while (iterator.hasNext()) {
consumer.accept(iterator.next(), counter);
counter++;
}
}
错误:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
at zad1.XList.forEachWithIndex(XList.java:126)
at zad1.Main.main(Main.java:89)