Java循环删除集合多个元素的正确打开方式
生活随笔
收集整理的這篇文章主要介紹了
Java循环删除集合多个元素的正确打开方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
首先說下不正確的打開方式:
第一:使用for循環(huán)刪除集合的元素,示例代碼如下
1 ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d")); 2 for (int i = 0; i < list.size(); i++) { 3 list.remove(i); 4 } 5 System.out.println(list);結(jié)果輸出為:
[b, d]解說開始:
首先看下源碼:
1 public E remove(int index) { 2 rangeCheck(index); 3 modCount++; 4 E oldValue = elementData(index); 5 int numMoved = size - index - 1; 6 if (numMoved > 0) 7 System.arraycopy(elementData, index+1, elementData, index, 8 numMoved); 9 elementData[--size] = null; // clear to let GC do its work 10 return oldValue; 11 }解釋:第一次進for循環(huán),i=0 ,調(diào)用remove方法刪除第一位的元素,?集合大小收縮,第一次刪除完成后,list變成【b,c,d】;再次循環(huán),i=1,調(diào)用remove方法刪除了c 集合大小再次收縮,list變成【b,d】;再次循環(huán),i=2,不符合條件,循環(huán)結(jié)束
第二:使用foreach循環(huán)刪除元素,示例代碼如下
1 ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d")); 2 for (String s : list) { 3 if (s.equals("b")) 4 list.remove(s); 5 } 6 System.out.println(list);結(jié)果:這段代碼居然拋出了異常?java.util.ConcurrentModificationException。?
解說開始:
首先看下源代碼:
1 public Iterator<E> iterator() { 2 return new Itr(); 3 } 4 /** 5 * An optimized version of AbstractList.Itr 6 */ 7 private class Itr implements Iterator<E> { 8 int cursor; // index of next element to return 9 int lastRet = -1; // index of last element returned; -1 if no such 10 int expectedModCount = modCount; 11 public boolean hasNext() { 12 return cursor != size; 13 } 14 @SuppressWarnings("unchecked") 15 public E next() { 16 checkForComodification(); 17 int i = cursor; 18 if (i >= size) 19 throw new NoSuchElementException(); 20 Object[] elementData = ArrayList.this.elementData; 21 if (i >= elementData.length) 22 throw new ConcurrentModificationException(); 23 cursor = i + 1; 24 return (E) elementData[lastRet = i]; 25 } 26 public void remove() { 27 if (lastRet < 0) 28 throw new IllegalStateException(); 29 checkForComodification(); 30 try { 31 ArrayList.this.remove(lastRet); 32 cursor = lastRet; 33 lastRet = -1; 34 expectedModCount = modCount; 35 } catch (IndexOutOfBoundsException ex) { 36 throw new ConcurrentModificationException(); 37 } 38 } 39 final void checkForComodification() { 40 if (modCount != expectedModCount) 41 throw new ConcurrentModificationException(); 42 } 43 }解釋:在Java中的foreach循環(huán)的工作原理就像一個iterator。
首次進入到foreach循環(huán)時,ArrayList創(chuàng)建一個內(nèi)部迭代器類對象,以后循環(huán)就不再創(chuàng)建。每次循環(huán)的流程都是先調(diào)用迭代器對象的hasNext()方法,返回true,再調(diào)用next()方法,而每次調(diào)用next()方法時,首先會檢測集合修改。 迭代器對象的實例字段就是檢測的關(guān)鍵所在。實例字段在創(chuàng)建對象時賦值了一次,后面就沒有再維護。 而調(diào)用remove(Object obj)方法時,集合本身跟蹤改寫操作(添加或者刪除),ArrayLis類對象維護一個改寫的變量,獨立于迭代器對象維護的計數(shù)值。 內(nèi)部迭代器類對象next()方法首先,判斷集合的改寫變量是否等于迭代器的改寫值,不等于就拋出異常。 PS: 在測試中發(fā)現(xiàn),若remove的是集合的倒數(shù)第二個元素或者最后一個元素,不會拋出異常。因為在remove以后,迭代器指向集合的末尾,再進入循環(huán)時,hasNext()方法返回false。循環(huán)結(jié)束。so,接下來說下正確的打開方式——
方法一:用傳統(tǒng)for循環(huán),從集合最后元素向前循環(huán)刪除元素,集合的size會變小,連帶索引都會改變,但不會影響到前面的未循環(huán)元素。 示例代碼如下 1 ArrayList<Integer> a=new ArrayList<Integer>(15); 2 a.add(222); 3 a.add(3); 4 a.add(333); 5 a.add(000); 6 a.add(333); 7 a.add(4); 8 9 for(int s=a.size()-1;s>=0;s--){ 10 if(a.get(s).intValue()==333){ 11 a.remove(s); 12 } 13 }?
方法二:使用Iterator的remove()方法刪除集合中的元素??示例代碼如下 1 privatevoid screenBlackNameList(List<SharedBoardSmsWrapper> source, List<BlackNameListModel> blackNameList){ 2 Iterator<SharedBoardSmsWrapper> sourceIt=source.iterator(); 3 while(sourceIt.hasNext()){ 4 SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next(); 5 Iterator<BlackNameListModel> blackNameListIt=blackNameList.iterator(); 6 while(blackNameListIt.hasNext()){ 7 BlackNameListModel tmpBlackNameListModel=blackNameListIt.next(); 8 if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){ 9 sourceIt.remove(); 10 break; 11 } 12 } 13 } 14 }?
? ? ?轉(zhuǎn)載于:https://www.cnblogs.com/mayiwen/p/5530856.html
總結(jié)
以上是生活随笔為你收集整理的Java循环删除集合多个元素的正确打开方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【HDU 5532 Almost Sor
- 下一篇: poi 读取excel