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三个元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值