文章目录
- for循环删除ArrayList中的某个值
- Iterator删除ArrayList中的某个值
- 来看看ConcurrentModificationException错误的产生原因
- 而对于iterator的remove方法
for循环删除ArrayList中的某个值
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29public static void main(String[] args) { ArrayList<Integer> arrayList = new ArrayList<>(); arrayList.add(1); arrayList.add(1); arrayList.add(2); arrayList.add(2); arrayList.add(3); arrayList.add(4); /** * 正序搜索删除 */ for (int i = 0; i <arrayList.size()-1;i++) { if(arrayList.get(i).equals(1)){ arrayList.remove(i); } } System.out.println("正序"+arrayList); /** * 反序搜索删除 */ for (int i = arrayList.size()-1; i >=0; i--) { if(arrayList.get(i).equals(2)){ arrayList.remove(i); } } System.out.println("反序"+arrayList); }
执行结果如下
可以发现正序删除并没能删除所有的1,而反序则可以完全删除所有的2。
因为ArrayList删除一个元素后,所有的元素都会向前移动,所以就会导致连续的1,并没能完全删掉。而后序遍历,删除,并不会影响前一个节点的值,所以可以完全删除。
Iterator删除ArrayList中的某个值
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38public static void main(String[] args) { ArrayList<Integer> arrayList = new ArrayList<>(); arrayList.add(1); arrayList.add(1); arrayList.add(2); arrayList.add(2); arrayList.add(3); arrayList.add(4); /** * arrayList删除 */ Iterator<Integer> iterator = arrayList.iterator(); try { while(iterator.hasNext()){ Integer next = iterator.next(); if(next.equals(1)){ arrayList.remove(next); } } } catch (Exception e) { e.printStackTrace(); } System.out.println(arrayList); /** * iterator删除 */ Iterator<Integer> iterator2 = arrayList.iterator(); while (iterator2.hasNext()) { Integer next = iterator2.next(); if(next.equals(2)){ iterator2.remove(); } } System.out.println(arrayList); }
执行结果如下
可以发现上面的iterator使用ArrayList删除元素,删除成功了,但是在删除第二之前时候(不是其没能力删除),好像就报了ConcurrentModificationException的错误。
而下面的iterator删除集合元素的方法就成功了,并不会报错。
来看看ConcurrentModificationException错误的产生原因
来看一下iterator方法在ArrayList方法中的内部实现,这里的modCount代表的就是最开始创建iterator的时候,集合的size大小。然后将其赋给了expectedModCount,即期待的modCount值。
接下来,对checkForComodification方法进行debug
可以发现,当在使用ArrayList删除后,modCount就会发生改变,期待的值不是6了,于是这里产生了异常,故抛出异常
而对于iterator的remove方法
可以发现,其调用的虽然是ArrayList的删除方法,但它在后面更新了新的expectedModCount,使得每次两个都能相等,这样就不会抛出异常了。能正常执行下去。
最后
以上就是简单百合最近收集整理的关于ArrayList的for循环删除和iterator循环删除的全部内容,更多相关ArrayList内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复