【源码解读】从ArrayList.class中解读为什么foreach中不能移除ArrayList元素

       一直听别人讲,对ArrayList,通过for循环和foreach循环来remove集合中的元素,前者不会报错,后者会报错,但是一直没有尝试,今天正好上午在深入Collection学习,就自己尝试验证一下。


一、代码实例

       要求:

       在循环中,移除ArrayList中的元素


       代码实例1:

public static void main(String[] args) {
	
	//创建list代码
	List<String> list1 = new ArrayList<String>();
    list1.add("张振华");
    list1.add("王振华");
    list1.add("李振华");
    list1.add("赵振华");
    list1.add("刘振华");
    list1.add("何振华");
    list1.add("高振华");
	System.out.println(list1);
	
	//通过for循环来删除(和foreach二选一)
	for(int i=0;i<list1.size();i++){
		if("张振华".equals(list1.get(i))){
			list1.remove(i);
		}
	}
	System.out.println(list1);

}
      输出结果:(成功)
     


     实例代码2:

public static void main(String[] args) {
	
	//创建list代码
	List<String> list1 = new ArrayList<String>();
    list1.add("张振华");
    list1.add("王振华");
    list1.add("李振华");
    list1.add("赵振华");
    list1.add("刘振华");
    list1.add("何振华");
    list1.add("高振华");
	System.out.println(list1);
	
	//通过for循环来删除(和foreach二选一)
    Integer i;
	for(i=0;i<list1.size();i++){
		if("张振华".equals(list1.get(i))){
			list1.remove(i);
		}
	}
	System.out.println(list1);

}
       输出结果:(失败)

      


      代码实例3:

public static void main(String[] args) {

    //创建list代码
    List<String> list1 = new ArrayList<String>();
    list1.add("张振华");
    list1.add("王振华");
    list1.add("李振华");
    list1.add("赵振华");
    list1.add("刘振华");
    list1.add("何振华");
    list1.add("高振华");
    System.out.println(list1);

    //通过foreach循环来删除(对比上述的for循环)
    for (String temp : list1) {
        if ("张振华".equals(temp)) {
            list1.remove(temp);
        }
    }
    System.out.println(list1);
}
        执行报错,如下:

       

       由此可见,在分别执行了3种情况的循环移除ArrayList集合元素的例子后,使用for循环,可以成功移除掉集合中的元素,但是实例2没有删掉;使用foreach,直接报错。


二、分析
       1.“实例代码2”为什么没有remove掉集合元素?
       针对“实例代码2”,为什么没有成功的移除掉ArrayList中的元素,参考ArrayList源码中的remove方法:

public E remove(int index) {  //传入的index值为int类型
	rangeCheck(index);
	checkForComodification();
	E result = parent.remove(parentOffset + index);
	this.modCount = parent.modCount;
	this.size--;
	return result;
}

public void remove() {
	if (lastRet < 0)
		throw new IllegalStateException();
	checkForComodification();

	try {
		ArrayList.this.remove(lastRet);
		cursor = lastRet;
		lastRet = -1;
		expectedModCount = modCount;
	} catch (IndexOutOfBoundsException ex) {
		throw new ConcurrentModificationException();
	}
}

private void rangeCheck(int index) {
    if (index < 0 || index >= this.size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
       可见,预期情况是,调用remove方法之后,跳入如上的“public E remove(int index)”方法中,但是实际上:
    

       java本身认为你传的参数是一个Object(Integer确实不是基本类型,属于Object对象),于是跳到了remove的重载方法,找到了这个尴尬的原因。


      2.“实例代码3”使用foreach()为什么直接报错?
      在跟代码的过程中,步入发现底层在这里抛出了异常:

         

         (图1.1)


         而且抛出的这个异常checkForComodification()就是在ArrayList源码中的“Itr”这个内部类当中,Itr如下:

/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return --用于返回下一个元素的索引
    int lastRet = -1; // index of last element returned; -1 if no such -- 返回最后一个元素的索引
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {  
        if (modCount != expectedModCount) //上述代码报错的地方
            throw new ConcurrentModificationException();
    }
}

       之后,演示跳进remove之后的执行套路:
       1.进入remove方法

/**
* Removes the first occurrence of the specified element from this list,
* if it is present.  If the list does not contain the element, it is
* unchanged.  More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists).  Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

        2.当传入的object和elementData[index]匹配之后,进行fastRemove(index)方法:

/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}

       追踪到在fastRemove()方法中,有一个全局变量modCount;而且在图1.1所示的报错信息中,也是因为modCount和expectMod值不同所引起来的,这就是报异常所在的原因!!
       
       反思:expectedModCount和modCount究竟是什么???
      (1)modCount
       在jdk1.8中,因为ArrayList继承自AbstractList:

public class ArrayList<E> extends AbstractList<E>
       在AbstractList中,找到了modCount的定义:

/**
* The number of times this list has been <i>structurally modified</i>.
* Structural modifications are those that change the size of the
* list, or otherwise perturb it in such a fashion that iterations in
* progress may yield incorrect results.
*/    
protected transient int modCount = 0;
        可知,modCount便令的作用是用于记录集合被修改的次数。而expectedModCount则是定义在内部类Itr中的变量:
private class Itr implements Iterator<E> {
	int cursor;       // index of next element to return
	int lastRet = -1; // index of last element returned; -1 if no such
	int expectedModCount = modCountmodCount;
        是预期的集合被修改次数。
   
        当程序执行到上述的fastRemove()中时:

private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}
        此时,modCount值被修改,比之前多了1。

        然而继续跟踪代码,之后回跳到内部类Itr的checkForComodification()方法中,此时会比较:

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}
       之后,就崩掉了。


       也就是说,如果使用foreach循环的时候,切记不能再其中remove集合元素,因为使用foreach遍历,本身会在ArrayList内部创建一个迭代器iterator,同时还有一个变量modCount,这两个值在每次遍历元素时会比较,而在执行remove方法之后,进入fastremove,就把modCount给修改了,之后就崩掉了。。。。。。

       所以,这就分析出了为什么在foreach中不要移除元素。
       

       That's all.
     





评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值