java ArrayList.remove 和 Iterator.remove 區別


foreach 遍歷 ArrayList 的時候  用ArrayList.remove 做刪除操作會異常的

直接用 Iterator 遍歷  Iterator.remove  是不會異常的

眾所周知,foreach 本質上就是 Iterator 的語法糖    那么為什么會出現這種情況呢?

 ArrayList 的  Iterator 返回的是 Itr 類的實例

public Iterator<E> iterator() {
return new Itr();
}


實例化Itr的時候 記錄了一個變量
int expectedModCount =modCount;

其中 modCount 是ArrayList的屬性 expectedModCount 是Itr的屬性
ArrayList.add   ArrayList.remove 等操作  都執行了 modCount++; 操作
就是說
expectedModCount 記錄的是 new Itr 之前的ArrayList修改操作次數
至於之后做的 modCount++; 則不知道
然鵝,每次Itr.next() 操作中  都判斷了 
if (modCount != expectedModCount)
throw new ConcurrentModificationException();

哈哈 找到foreach報錯原因了吧


那么 為什么 Iterator.remove 不報錯呢? 實際上
Iterator.remove內部也調用了ArrayList.remove 只不過后面又執行了 expectedModCount=modCount 










免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM