System.arraycopy

ArrayList源码中的删除

 /*
     * 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
    }

这一操作中的System.arraycopy目标数组和源数组都是同一个,因此并不需要额外的空间

public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

src:源数组; 
srcPos:源数组要复制的起始位置; 
dest:目的数组; 
destPos:目的数组放置的起始位置; 
length:复制的长度。 
注意:src and dest都必须是同类型或者可以进行转换类型的数组.

 public static void main(String[] args) {
        String src[] = new String[] { "hello", "huang", "bao", "kang" };
        String dest[] = new String[5];
        System.arraycopy(src, 0, dest, 0, 4);
        for (String str : dest) {
            System.out.println(str);
        }
        System.out.println("=========华丽的分割线=========");
        System.arraycopy(src, 0, src, 1, 3);
        for (String str : src) {
            System.out.println(str);
        }
    }

结果:

hello
huang
bao
kang
null
=========华丽的分割线=========
hello
hello
huang
bao

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值