【发布时间】:2012-01-03 16:29:26
【问题描述】:
我一直在研究这个 sn-p 代码。这是我想要发生的伪代码:
a.检查节(这是一个列表)大小是否为 0。
b.如果section size为0,则通过调用sections.add(newSection)
自动将学生注册到该section
c.else 如果节大小不为零,请检查是否与调度冲突
d.如果没有冲突,则通过调用sections.add(newSection)
将学生注册到该部分
e.else什么都不做
Java 不断向我抛出“java.util.concurrentmodificationexception”错误。我知道,我不应该在遍历列表时更改 ArrayList 的大小,因为它会修改迭代器。还有其他方法可以解决这个问题吗? :D
非常感谢。 非常感谢您的帮助。 :)
public String enrollsTo(Section newSection){
StringBuffer result = new StringBuffer();
String resultNegative = "Failed to enroll in this section.";
String resultPositive = "Successfully enrolled in section: " + newSection.getSectionName() + ".";
int previousSectionSize = sections.size();
if(this.sections.isEmpty()){
this.sections.add(newSection);
result.append(resultPositive);
}else{
for(Iterator<Section> iterator = sections.iterator(); iterator.hasNext() ; ){
Section thisSection = iterator.next();
if(thisSection.conflictsDayWith(newSection)==false &&
thisSection.conflictsTimeWith(newSection)==false){
this.sections.add(newSection); //<-- i believe the problem lies here.
result.append(resultPositive);
}
}
}
// if(this.sections.size() == previousSectionSize){
// result.append(resultNegative);
// }
return result.toString();
}
【问题讨论】:
-
注意:你的逻辑是错误的。而不是“如果没有冲突”,您正在测试“为每个不冲突的部分添加一个新部分”。
-
hmm..所以这就是为什么它看起来有点错误和奇怪。您必须指出,必须以某种方式对其进行改进,感谢您指出。 :D
标签: java concurrentmodification