over 4 years ago

底下當 learners.remove 時會出現 java.util.ConcurrentModificationException
原因是再each刪除陣列元素後 index 指標溢位的問題
因為 each 執行中不會檢查陣列數的變化

for(Object learner : learners){
    RecordObject user = (RecordObject)learner;
    if(ignoreList.contains(user.getInt("UserId"))){
        learners.remove(learner);
    }
}

改寫方式一 使用 for

for(int i = 0; i < learners.size(); i++){
    RecordObject user = (RecordObject)learners.get(i);
    int sessionId = user.getInt("SessionId");
    int courseId = user.getInt("CourseId");
    int userId = user.getInt("UserId");

    if(isTRLearnerBy(courseId, sessionId, userId) && !ignoreList.contains(user.getInt("UserId"))){
        learners.remove(i);
        i = i - 1; // 因 for 最後會做 i++ 所以必須將 i 維持在刪除時 index 再往下
    }
}

改寫方式二 使用 Iterator

Iterator<RecordObject> sListIterator = learners.iterator(); 
while(sListIterator.hasNext()){
    RecordObject user = (RecordObject)sListIterator.next();
    int sessionId = user.getInt("SessionId");
    int courseId = user.getInt("CourseId");
    int userId = user.getInt("UserId");

    if(isTRLearnerBy(courseId, sessionId, userId) && !ignoreList.contains(user.getInt("UserId"))){
        sListIterator.remove();
    }
}
← Validate Plugin 解決 document.referrer 網址變動問題 →
 
comments powered by Disqus