首先说下不正确的打开方式:
第一:使用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 }