在迭代期間刪除集合元素時避免ConcurrentModificationException
簡介
簡介
方法 1:迭代集合副本
一種方法是建立集合的副本並迭代該副本而不是原始集合。這可以確保原始集合在迭代過程中不會被修改。
List<Foo> fooListCopy = new ArrayList<>(fooList); for (Foo foo : fooListCopy) { // Modify the actual fooList }
方法2:使用集合迭代器
另一種方法是使用原始集合迭代器
Iterator<Foo> itr = fooList.iterator(); while (itr.hasNext()) { // Modify the actual fooList using itr.remove() }
範例:
removeIf:
此方法採用謂詞並從集合中刪除滿足謂詞的所有元素。以上是在迭代過程中從集合中刪除元素時如何避免 ConcurrentModificationException?的詳細內容。更多資訊請關注PHP中文網其他相關文章!