java 字节数组 byte[] 复制方法_1分钟学习Java中数组快速复制

本文介绍Java中使用System.arraycopy和Arrays.copyOf方法实现数组的快速复制。System.arraycopy能够高效地从源数组复制元素到目标数组;而Arrays.copyOf则可以创建并返回一个指定长度的新数组,新数组会包含原数组的部分或全部元素。

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

111b66685676e6933dee0116893a1510.png

Java System类提供了的arraycopy快速复制数组方法。具体函数如下:

public class ArrayCopyTest {    public static void main(String[] args) {        int[] arr = {1, 2, 3};        int[] destArr = new int[arr.length];        System.arraycopy(arr, 0, destArr, 0, arr.length);    }}

example:

/** * @param  the class of the objects in the original array * @param  the class of the objects in the returned array * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls *     to obtain the specified length */ public static  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;    } 

Java Arrays.copyOf()使用

/** * @param  the class of the objects in the original array * @param  the class of the objects in the returned array * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls *     to obtain the specified length */ public static  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;    } 

以上就是Java数组的快速复制。你学会了吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值