【发布时间】:2012-06-19 05:48:27
【问题描述】:
如果有以下问题: 我有一个列表,我正在使用增强的 for 循环。每次我想从列表中删除某事时,我都会得到一个 ConcurrentModificationException。我已经知道为什么会抛出这个异常,但我不知道如何修改我的代码,以便它工作。这是我的代码:
for(Subject s : SerData.schedule)
{
//Checking of the class is already existing
for(Classes c : s.classes)
{
if(c.day == day &c.which_class == which_class)
{
int index = getclassesindex(s.classes, new Classes(day, which_class));
synchronized (s) {
s.classes.remove(index);
}
}
}
//More code....
}
我也尝试了这个实现。
for(Subject s : SerData.schedule)
{
//Checking of the class is already existing
Iterator<Classes> x = s.classes.iterator();
while(x.hasNext())
{
Classes c = x.next();
if(c.day == day &c.which_class == which_class)
{
int index = getclassesindex(s.classes, new Classes(day, which_class));
synchronized (s) {
s.classes.remove(index);
}
}
}
//More code....
}
也不行……
是否有常用的标准解决方案? (希望……这并不明显:D)
【问题讨论】:
-
您是否错过了键入复制的代码,或者您的意思是在 if 语句(即单个 &)中按位和,我认为您应该有 &&
-
我有 &&,打错字了...sry
标签: java for-loop concurrentmodification