0
点赞
收藏
分享

微信扫一扫

Java中数组复制的常见方法


代码演示

import java.util.Arrays;

public class CopyArray {
public static void main(String[] args) {
// 继承Object类中的clone()方法
int[] a = {1,2,3,4};
int[] copyA = a.clone();

// System类中的方法
int[] cpA = new int[4];
System.arraycopy(a, 0, cpA, 0, 4);

// 使用数组工具中的方法
int[] cppA = Arrays.copyOf(a, 4);
int[] cppA1 = Arrays.copyOfRange(a, 0, 4);

// 通过for循环来赋值数组
int[] cpppA = new int[4];
for (int i = 0; i < a.length; i++) {
cpppA[i] = a[i];
}

a[0] = 12;
a[1] = 12; // 更改原数组对所复制的数组没有影响

System.out.println(Arrays.toString(copyA)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cpA)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cppA)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cppA1)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cpppA)); // [1, 2, 3, 4]
}
}

方法分析

  1. for循环

通过遍历依次赋值新的数组即可,但效率不高,写的也麻烦


  1. System.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length)

这个方法就灵活很多,不但可以复制数组,还可以任意复制一个数组中任意部分到另一个数组.
还可以合并两个数组(前提两个数组中其中一个数组可以容纳两个数组的所有元素.

参数解释 :
src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目标数据中的起始位置。
length - 要复制的数组元素的数量。

  1. clone()方法

这个方法是从何而来呢?API中又没有数组的相关介绍.
你可以这样想,数组是对象吧,那么所有类的顶层父类都是Object类.
因此clone()方法存在于Object类中.

  1. Arryas.copyOf(int[] original, int newLength)

参数解释 :
original - 要复制的数组
newLength - 要返回的副本的长度

  1. Arrays.copyOfRange(int[] original, int from, int to)

参数解释 :
original - 将要从其复制一个范围的数组
from - 要复制的范围的初始索引(包括)
to - 要复制的范围的最后索引(不包括)。(此索引可以位于数组范围之外)。

  1. 效率问题

System.arraycopy > Arrays.copyOf(Arrays.copyOfRange) > for循环 > clone

  1. 深度分析参考

​​Java - 数组拷贝的几种方式​​


举报

相关推荐

0 条评论