久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

解決JAVA遍歷List集合,刪除數據時出現的問題

瀏覽:2日期:2022-08-29 09:52:44

一、問題描述

有時候,我們會遇到在遍歷List集合的過程中刪除數據的情況。

看著自己寫的代碼,感覺完全沒有問題,但就是達不到預期的效果,這是為什么呢?下面我們來分析下

String str1 = new String('1'); String str2 = new String('2'); String str3 = new String('3'); String str4 = new String('4'); String str5 = new String('5'); List list = new ArrayList(); list.add(str1); list.add(str2); list.add(str3); list.add(str4); list.add(str5); System.out.println('list.size()=' + list.size()); for (int i = 0; i < list.size(); i++) { list.remove(i);// i--; //System.out.println(i+' '+list.get(i)+' '); } System.out.println('after remove:list.size()=' + list.size());

本來預期結果應該是:

list.size()=5 after remove:list.size()=0

但實際上結果卻是:

list.size()=5 after remove:list.size()=2

原因如下: List每remove掉一個元素以后,后面的元素都會向前移動 ,此時如果執行i++,則剛剛移過來的元素沒有被讀取。

分析:

List中有5條數據,需要循環5次, 第一次數據為:1 2 3 4 5 執行完remove(0) 后,數據為 2 3 4 5 , i=1 第二次數據為:2 3 4 5 執行完remove(1) 后,數據為 2 4 5 , i=2 第三次數據為:2 4 5 執行完remove(2) 后,數據為 2 4 , i=3 此時如果加上上面注釋的代碼 System.out.println(i+' '+list.get(i)+' '); 循環第4、5次時就會出現異常

二、解決方法

解決方法1:每移過一次后,再把 i 移回來

for (int i = 0; i < list.size(); i++) { list.remove(i);i--; }

解決方法2:先刪除后面的元素

for (int i = list.size()-1; i >= 0; i--) { list.remove(i); }

解決方法3:使用iterator刪除

for(Iterator it = list.iterator();it.hasNext();){ it.remove(); }

以上就是解決JAVA遍歷List集合時,刪除數據出現的問題的詳細內容,更多關于JAVA遍歷List集合 刪除數據的資料請關注好吧啦網其它相關文章!

標簽: Java
主站蜘蛛池模板: 新丰县| 长垣县| 平遥县| 武清区| 巨野县| 德庆县| 日照市| 日土县| 大关县| 宜良县| 铜陵市| 科技| 黔西县| 巴中市| 清水河县| 远安县| 鄯善县| 广南县| 望都县| 阜宁县| 兴仁县| 勐海县| 溧水县| 罗定市| 云林县| 乌拉特前旗| 虞城县| 尼木县| 榆林市| 阜城县| 广灵县| 景谷| 昌平区| 长治县| 博野县| 修文县| 大邑县| 揭东县| 亳州市| 娱乐| 铜梁县|