java集合遍历删除元素_Java循环删除集合多个元素的正确打开方式

首先说下不正确的打开方式:

第一:使用for循环删除集合的元素,示例代码如下

1 ArrayList list = new ArrayList(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(intindex) {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 returnoldValue;11 }

解释:第一次进for循环,i=0 ,调用remove方法删除第一位的元素, 集合大小收缩,第一次删除完成后,list变成【b,c,d】;再次循环,i=1,调用remove方法删除了c 集合大小再次收缩,list变成【b,d】;再次循环,i=2,不符合条件,循环结束

第二:使用foreach循环删除元素,示例代码如下

1 ArrayList list = new ArrayList(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 Iteratoriterator() {2 return newItr();3 }4 /**

5 * An optimized version of AbstractList.Itr6 */

7 private class Itr implements Iterator{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 booleanhasNext() {12 return cursor !=size;13 }14 @SuppressWarnings("unchecked")15 publicE next() {16 checkForComodification();17 int i =cursor;18 if (i >=size)19 throw newNoSuchElementException();20 Object[] elementData = ArrayList.this.elementData;21 if (i >=elementData.length)22 throw newConcurrentModificationException();23 cursor = i + 1;24 return (E) elementData[lastRet =i];25 }26 public voidremove() {27 if (lastRet < 0)28 throw newIllegalStateException();29 checkForComodification();30 try{31 ArrayList.this.remove(lastRet);32 cursor =lastRet;33 lastRet = -1;34 expectedModCount =modCount;35 } catch(IndexOutOfBoundsException ex) {36 throw newConcurrentModificationException();37 }38 }39 final voidcheckForComodification() {40 if (modCount !=expectedModCount)41 throw newConcurrentModificationException();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 a=new ArrayList(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 source, ListblackNameList){2 Iterator sourceIt=source.iterator();3 while(sourceIt.hasNext()){4 SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next();5 Iterator 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 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值