close

今天程式發生了一個罕見的例外:java.util.ConcurrentModificationException
程式的大致內容如下:

for (TreeWindowModel child : childs) {
    // 判斷子點是否為葉節點
    if (child != null && child.getChilds().size() == 0) {
        // 如果是葉節點且無權限者,移除
        if (!child.hasAuth) {
            childs.remove(child);
        }
    } else {
        child.clearNoAuthLeaf();
    }
}

程式的錯誤指向 for (TreeWindowModel child : childs) 這一行,一時之間還真不知道發生什麼錯誤,後來 Eric (感謝 Eric啦!)在 http://www.blogger.com/post-create.g?blogID=4690814976841013329 找到這篇文章,內容是說

『在 Map 或者 Collection 的時候,不要用它們的 API 直接修改集合的內容,如果要修改可以用 Iterator的 remove() 方法』

因此將上述的程式改成:

for (Iterator it = childs.iterator(); it.hasNext();){
    TreeWindowModel child = it.next();
    if (child != null && child.getChilds().size() == 0) {
        // 如果是葉節點且無權限者,移除
        if (!child.hasAuth) {
            it.remove();
        }
    } else {
        child.clearNoAuthLeaf();
    }
}

這樣程式就不再丟出 java.util.ConcurrentModificationException

arrow
arrow
    全站熱搜

    大笨鳥 發表在 痞客邦 留言(0) 人氣()