我一直在研究這段代碼。這是我所希望發生的僞代碼:我一直在得到java.util.concurrentmodificationexception ..如何解決這個問題?
答。查看,如果部分(這是一個列表)大小爲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();
}
注:您的邏輯被打破了。而不是「如果沒有衝突」,你正在測試「每個不衝突的部分添加一個新的部分」。 – Howard 2012-01-03 16:36:32
嗯..所以這就是爲什麼它看起來有點錯誤和怪異。你必須指出,得以改進它,謝謝指出。 :d – 2012-01-03 16:39:56