ArrayList remove()元素遇到的问题

问题:
下面两种方法remove数组中的元素:

public class ArrayListDemo{
public static void main(String[] args){
	ArrayList<String>list=new Arraylist(); 
	list. add("a");
	1ist. add("b");
	1ist. add("c");
	1ist. add("e");
	1ist. add("f");
	1ist. add("g"); 
	for(int i=0;i<list. size();i++){//
		list. remove(i); 
		System. out. println("list. size:"+list. size());  //输出:3
	}
}
public class ArrayListDemo{
public static void main(String[] args){
		ArrayList<String>list=new Arraylist(); 
		list. add("a");
		1ist. add("b");
		1ist. add("c");
		1ist. add("e");
		1ist. add("f");
		1ist. add("g"); 
		for(int i=list. size()-1;i>=0;i--){//
			list. remove(i); 
			System. out. println("list. size:"+list. size());  //输出:0
		}
	}
}

为什么会出现上面的情况呢?
分析源码:

    public E remove(int index) {
        rangeCheck(index);  //判断符合删除数组规则

        modCount++;
        //取出即将删除的元素
        E oldValue = elementData(index);
        //需要需要移动的元素
        int numMoved = size - index - 1;
        //如果需要移动你的元素>0
        if (numMoved > 0)
        //数组的拷贝
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue; //返回被删除䣌元素
    }

其中核心方法:
public static native void arraycopy(Object src,int srcPos,Object dest, int destPos,int length);
实现和数组之间的拷贝

* @param      src      the source array. 源数组
* @param      srcPos   starting position in the source array. 源数组的起始位置
* @param      dest     the destination array. 目标数组
* @param      destPos  starting position in the destination data. 目标数组的起始位置
* @param      length   the number of array elements to be copied. 复制的长度

这样就可以解释:
在这里插入图片描述
最后只剩下b,d,f三个元素。

发布了43 篇原创文章 · 获赞 5 · 访问量 2656

猜你喜欢

转载自blog.csdn.net/JAYU_37/article/details/104425830