iterator for遍歷集合的優缺點

2021-09-28 20:55:47 字數 435 閱讀 9244

iterator(for each):遍歷適合移出元素

for:遍歷適移出元素會報錯

為什麼用iterator刪除元素不拋異常,而用for刪除會拋異常呢?

這主要是因為arraylist每次遍歷的時候會去判斷該集合是否被修改過,呼叫的方法是checkforcomodification()。 如果被修改過concurrentmodificationexception異常。

如何判斷是否修改呢,主要是通過維護2個變數來實現,modcount記錄了修改次數,expectedmodcount記錄期望修改次數。 通過iterator.remove()進行的刪除操作,會同時修改modcount、concurrentmodificationexception; 而通過list.remove(object/index),則只會修改modcount。 這也是fast-fail機制。

參考:

java List Set Map集合遍歷

遍歷集合的方式無非就是使用for迴圈,增強for迴圈或迭代器這幾種方式。1.遍歷list list遍歷 author zc public class testlist iterator it set.iterator while it.hasnext 在使用增強for迴圈遍歷時,採用這種結構訪問 f...

Kotlin Set集合遍歷

就是整理了遍歷的方法 很簡單 fun main args array println for i in hashsetof println 遍歷方式2 foreach 因為set集合繼承了iteratable 所以可以使用該介面的foreach方法 有序和無序都適用 mutablesetof.for...

HashMap集合遍歷

map的遍歷 1,迭代器 一鍵導包 ctrl shift o 先遍歷出key 再通過key找到value set keyset map.keyset 因為map中的key是唯一的 所以可以獲取到key的set集合 iterator it keyset.iterator 獲取迭代器 while it....