在Android上做List Remove的时候遇到的异常

目的是从createdList里面找到匹配的pendingStatusList,并将其从pendingStatusList中remove

for (DocSyncStatus pendingDss : pendingStatusList) {
        for (DocSyncStatus createdDss : createdList) {
            if (pendingDss.getDocHash().equals(createdDss.getDocHash())) {
                // add into the res list to delete them from the DB.		                     
                successDocStatusRes.add(pendingDss);
                Log.i(TAG, "find the pending doc in the docsync cloud server by syncDoc,pendingDss=" + pendingDss);
                pendingStatusList.remove(pendingDss);
            }
        }
    }



上述代码会报异常: java.util.ConcurrentModificationException

从http://blog.csdn.net/aa4790139/article/details/6438869这里找到了原因,并改为如下版本:

for (Iterator it = pendingStatusList.iterator(); it.hasNext();) {
            DocSyncStatus pendingDss = (DocSyncStatus) it.next();
            for (DocSyncStatus createdDss : createdList) {
                if (pendingDss.getDocHash().equals(createdDss.getDocHash())) {
                    // add into the res list to delete them from the DB.
                    successDocStatusRes.add(pendingDss);
                    Log.i(TAG, "find the pending doc in the docsync cloud server by syncDoc,pendingDss=" + pendingDss);
                    
                    it.remove();
                }
            }
        }



上述版本第二次remove的时候,报异常:  java.lang.IllegalStateException

从http://stackoverflow.com/questions/13539716/java-error-when-removing-from-an-arraylist-more-than-once-illegalstateexcept 这里找到了解决方案:

for (Iterator<DocSyncStatus> it = pendingStatusList.iterator(); it.hasNext();) {
            DocSyncStatus pendingDss = (DocSyncStatus) it.next();
            for (DocSyncStatus createdDss : createdList) {
                if (pendingDss.getDocHash().equals(createdDss.getDocHash())) {
                    // add into the res list to delete them from the DB.
                    successDocStatusRes.add(pendingDss);
                    Log.i(TAG, "find the pending doc in the docsync cloud server by syncDoc,pendingDss=" + pendingDss);
                    
                    it.remove();
                }
            }
        }


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。