主要有以下3种方法:
- 使用Iterator的remove()方法
- 使用for循环正序遍历
- 使用for循环倒序遍历
1. 使用Iterator的remove()方法
public static void main(String[] args) { List<String> platformList = new ArrayList<>(); platformList.add("博客园"); platformList.add("CSDN"); platformList.add("掘金"); Iterator<String> iterator = platformList.iterator(); while (iterator.hasNext()) { String platform = iterator.next(); if (platform.equals("博客园")) { iterator.remove(); } } System.out.println(platformList); }
每次删除一个元素,都会将modCount的值重新赋值给expectedModCount,这样2个变量就相等了,不会触发java.util.ConcurrentModificationException异常。
2. 使用for循环正序遍历
public static void main(String[] args) { List<String> platformList = new ArrayList<>(); platformList.add("博客园"); platformList.add("CSDN"); platformList.add("掘金"); for (int i = 0; i < platformList.size(); i++) { String item = platformList.get(i); if (item.equals("博客园")) { platformList.remove(i); i = i - 1; } } System.out.println(platformList); }
3. 使用for循环倒序遍历
public static void main(String[] args) { List<String> platformList = new ArrayList<>(); platformList.add("博客园"); platformList.add("CSDN"); platformList.add("掘金"); for (int i = platformList.size() - 1; i >= 0; i--) { String item = platformList.get(i); if (item.equals("掘金")) { platformList.remove(i); } } System.out.println(platformList); }
相关推荐
在Java编程中,遍历并删除List集合是一个常见的操作,但在实际编程中,如果不使用正确的方法,可能会导致`java.util.ConcurrentModificationException`异常。本文主要针对这个面试题,详细讲解如何在遍历List的同时...
因为写别的程序想要一边遍历一边删除列表里的元素,就写了一个这样的程序进行测试,这样写出来感觉还挺简洁的,就发出来分享一下。 代码 l=list(range(2,1000)) for n,i in enumerate(l): for j in l[n+1:]: if j...
但是,如果我们想一边迭代,一边删除集合中的元素,就需要使用 iterator 迭代器中的 remove() 方法,例如: ```java Iterator it = list.iterator(); while(it.hasNext()){ Object obj = it.next(); System.out....
在JavaScript中,链表节点通常包含数据和指向下一个节点的引用,通过遍历节点来执行操作。 哈希表(Hash Table)是一种通过键(Key)来快速查找数据的数据结构,它通过哈希函数将键映射到数组索引。JavaScript对象...
- Python有六种标准的数据类型:Number(数字)、String(字符串)、Tuple(元组)、List(列表)、Set(集合)、Dictionary(字典)。 - Number包括:int(整数)、float(浮点数)、bool(布尔型,True 和 False...
19. **List遍历删除元素** - 使用迭代器`Iterator`来遍历并删除元素,可以避免`ConcurrentModificationException`异常。 - `fail-fast`机制确保迭代过程中如果列表发生结构修改,则抛出异常。 - `fail-safe`机制...
- **解决方案**:使用迭代器的`remove()`方法安全地删除元素。 #### 48. HashSet如何保证元素唯一性 - **原理**:通过`hashCode()`和`equals()`方法来判断元素是否相等。 - **实现**:每个元素都会根据其`hashCode...