我一直在研究这段代码。这是我想要发生的事情的伪代码:
检查部分(列表)的大小是否为0。
b。如果部分大小为0,则通过调用sections.add(newSection)自动将学生注册为该部分
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();
}
最佳答案
不要在for循环内执行sections.add(newSection)
,因为这是对您当前正在迭代的集合的修改。
另外,在确定是否添加newSection
之前是否不想检查所有部分?也许是这样的:
boolean conflict = false;
for (...) {
if (/* check for conflict */) {
conflict = true;
break;
}
}
if (!conflict) {
sections.add(newSection);
}