Java中System.arraycopy和Arrays.copyOf

本文探讨了ArrayList扩容时使用的System.arraycopy()和Arrays.copyOf()方法。System.arraycopy()作为本地方法,性能更优,而Arrays.copyOf()在创建新数组时能自动指定类型,但可能涉及额外类型检查。在选择时需权衡效率与类型安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在ArrayList扩容机制中注意到,数组的深拷贝有用到两种方法:System.arraycopy()Arrays.copyOf()

比较

System.arraycopy()native方法,参数需要传递源数组和目标数组。

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

Arrays.copyOf()方法内部其实调用了System.arraycopy()方法

  public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

所以Arrays.copyOf()在数组自动扩容时可以很方便。理论上System.arraycopy()的性能肯定是优于Arrays.copyOf()的。但是注意到Arrays.copyOf()在自动创建数组时使用了源数组的Class。如果使用System.arraycopy()进行拷贝操作时源数组和目标数组类型并不完全一致(比如Object[]和String[])时,会额外有类型检查花销[stackflow]。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值