Java复制数组的4种方法:Arrays.copyOf(), Arrays.copyOfRange(), System.arraycopy(), object.clone()

参考:

C语言中文网

博客园cnblogs

代码:

int[] a = {1,2,3,4,5};

int[] b = Arrays.copyOf(a,10);           //有返回值
int[] c = Arrays.copyOfRange(a,3,8);     //有返回值
int[] d = new int[10];
System.arraycopy(a,0,d,1,3);             //没有返回值!
int[] e = a.clone();                     //有返回值

>>
b: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
c: [4, 5, 0, 0, 0]
d: [0, 1, 2, 3, 0, 0, 0, 0, 0, 0]
e: [1, 2, 3, 4, 5] 

区别:

Arrays.copyOf()和Arrays.copyOfRange()返回一个新建的对象,不需要预先建立对象,其实在方法内部调用了System.arraycopy()方法;

System.arraycopy()无返回值,需要先new一个对象作为方法的输入参数;

object.clone()方法返回一个新建的对象,不需要预先建立对象。(返回类型是Object类,可能需要进行强制类型转换)。

你可能感兴趣的:(Java)