日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

关于java.util.ConcurrentModificationException和remove倒数第二个元素

發布時間:2025/3/8 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于java.util.ConcurrentModificationException和remove倒数第二个元素 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

首先是兩段代碼的執行結果:

代碼一:

public class TestListRemove {public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);for (Iterator<Integer> it = list.iterator(); it.hasNext();) {Integer val = it.next();if (val == 1) {list.remove(val);}}for (Integer i : list) {System.out.println(i);}} }

代碼二:

public class TestListRemove {public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);for (Iterator<Integer> it = list.iterator(); it.hasNext();) {Integer val = it.next();if (val == 6) {list.remove(val);}}for (Integer i : list) {System.out.println(i);}} }

代碼一結果:

Exception in thread "main" java.util.ConcurrentModificationException
?? ?at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
?? ?at java.util.ArrayList$Itr.next(ArrayList.java:791)
?? ?at com.odling.test.TestListRemove.main(TestListRemove.java:21)
?

代碼二結果:

1
2
3
4
5
7
?

原因就是這里:

首先代碼一拋錯是這段代碼:

Integer val = it.next();?

final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}

這個異常網上很多文章就不說了。

AbsrtactList中iteraor方法返回一個內部類,這個類實現了iterator接口,hasNext()對cursor和list的size判斷。

關于cursor的參數說明:

int cursor; ? ? ? // index of next element to return

如果刪除了倒數第二個元素,拿代碼二舉栗子:cursor返回6,size因為被remove掉一個,所以也是6,hasNext()方法返回false,不會再執行Integer val = it.next(); ?所以代碼二沒有異常,但是元素確實被remove了。

public boolean hasNext() {return cursor != size();}

?

再來看一下對代碼一的改進:

public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);for (Iterator<Integer> it = list.iterator(); it.hasNext();) {try {Integer val = it.next();if (val == 1) {list.remove(val);}} catch (Exception e) {System.out.println("發生異常。");break;}}for (Integer i : list) {System.out.println(i);}}

結果:

發生異常。
2
3
4
5
6
7
?

發現元素確實已經被remove掉了。

轉載于:https://my.oschina.net/yZLZkvk6bjiN/blog/885272

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的关于java.util.ConcurrentModificationException和remove倒数第二个元素的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。