[英]ArrayList / for-loop
My problem is simple : listeBalles
is an ArrayList<Balle>
and here is my code :我的问题很简单:
listeBalles
是一个ArrayList<Balle>
,这是我的代码:
for (Balle b : listeBalles) {
b.changeList(listeBalles);
}
The matter is that the method b.changeList
adds a Balle to the ArrayList listeBalles
.问题是方法
b.changeList
将 Balle 添加到 ArrayList listeBalles
。 I think that this is the matter.我认为这就是问题所在。 Here are the exceptions :
以下是例外情况:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Main.main(Main.java:31)
The line pointed is the for (Balle b : listeBalles) {
line.指向的行是
for (Balle b : listeBalles) {
行。
Thank you for your help.感谢您的帮助。
Yes, you're right.你是对的。 From
ArrayList
's JavaDoc:来自
ArrayList
的 JavaDoc:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
此类的 iterator 和 listIterator 方法返回的迭代器是快速失败的:如果在创建迭代器后的任何时间以任何方式修改列表结构,除了通过迭代器自己的 remove 或 add 方法,迭代器将抛出 ConcurrentModificationException。
So basically you're not allowed to modify the List during iterating over it.所以基本上你不允许在迭代过程中修改 List。 What is your actual question?
你的实际问题是什么?
原因是您正在遍历List
并同时修改它。
You cannot modify the content of a collection or array while you iterate over it in a for-each loop.在 for-each 循环中迭代集合或数组时,不能修改它的内容。 What are you actually trying to do?
你究竟想做什么?
As you cannot add elements to an ArrayList
you're currently iterating over, make a copy of that list first.由于您无法向当前正在迭代的
ArrayList
添加元素,因此请先制作该列表的副本。
Eg try:例如尝试:
for (Balle b : new ArrayList(listeBalles)) {
b.changeList(listeBalles);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.