首先說下不正確的打開方式:
第一:使用for循環刪除集合的元素,示例代碼如下
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);
結果輸出為:
[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循環,i=0 ,調用remove方法刪除第一位的元素, 集合大小收縮,第一次刪除完成后,list變成【b,c,d】;再次循環,i=1,調用remove方法刪除了c 集合大小再次收縮,list變成【b,d】;再次循環,i=2,不符合條件,循環結束
第二:使用foreach循環刪除元素,示例代碼如下
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);
結果:這段代碼居然拋出了異常 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循環的工作原理就像一個iterator。
首次進入到foreach循環時,ArrayList創建一個內部迭代器類對象,以后循環就不再創建。每次循環的流程都是先調用迭代器對象的hasNext()方法,返回true,再調用next()方法,而每次調用next()方法時,首先會檢測集合修改。
迭代器對象的實例字段就是檢測的關鍵所在。實例字段在創建對象時賦值了一次,后面就沒有再維護。
而調用remove(Object obj)方法時,集合本身跟蹤改寫操作(添加或者刪除),ArrayLis類對象維護一個改寫的變量,獨立於迭代器對象維護的計數值。
內部迭代器類對象next()方法首先,判斷集合的改寫變量是否等於迭代器的改寫值,不等於就拋出異常。
PS:
在測試中發現,若remove的是集合的倒數第二個元素或者最后一個元素,不會拋出異常。因為在remove以后,迭代器指向集合的末尾,再進入循環時,hasNext()方法返回false。循環結束。
so,接下來說下正確的打開方式——
方法一:用傳統for循環,從集合最后元素向前循環刪除元素,集合的size會變小,連帶索引都會改變,但不會影響到前面的未循環元素。 示例代碼如下
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 }