List 集合remove问题
生活随笔
收集整理的這篇文章主要介紹了
List 集合remove问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java的list集合中。使用remove刪除元素:
方法一:
static List<Integer> list3 = new ArrayList<Integer>(); static {list3.add(1);list3.add(2);list3.add(2);list3.add(2);list3.add(2); } private static void remove(List<Integer> list3) {for (int i=0;i<list3.size();i++) {if(list3.get(i) == 2) {list3.remove(i);}}print(list3); }打印結果:1。2。2
造成問題的解決辦法是,在使用remove刪除list中元素時,list集合的size會發生變化。所以不能達到預期。
方法二:
private static void remove(List<Integer> list3) {for(int i = 0 , len= list3.size();i<len;++i){ if(list3.get(i)==2){ list3.remove(i); --len;//降低一個 --i;//多謝deny_guoshou指正,假設不加會出現評論1樓所說的情況。 } } print(list3); }打印結果:1
因為動態的計算list大小,所以能夠得到正確答案
方法三:
Iterator<String> sListIterator = list.iterator(); while(sListIterator.hasNext()){ String e = sListIterator.next(); if(e.equals("3")){ sListIterator.remove(); } }List接口內部實現了Iterator接口。提供開發人員一個iterator()得到當前list對象的一個iterator對象。注:對于并發情況,更因該使用第三種方法(迭代器)。否則一定會出現并發問題。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的List 集合remove问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DHCP服务_学习笔记
- 下一篇: bash參考手冊之六(Bash特性)