复制数组的几种方式

简介: 复制数组的几种方式

遍历复制

通过遍历数组,遍历的过程中把原数组中的数据复制到新的数组中

System.arraycopy

源码:


 * @param      src      the source array. //原数组
 * @param      srcPos   starting position in the source array. //在原数组中开始复制的位置
 * @param      dest     the destination array. //目标数组
 * @param      destPos  starting position in the destination data.//目标数组中开始的位置
 * @param      length   the number of array elements to be copied.//要复制的数组元素的数量
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);


实例


        int[] arr = {1,2,3,4,5,6,7};
        int[] arr1 = new int[7];
        System.out.println(Arrays.toString(arr1));
        System.arraycopy(arr,0,arr1,0,7);
        System.out.println(Arrays.toString(arr1));


输出:


[0, 0, 0, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 6, 7]



Arrays.copyOf


源码:


需要注意的是该方法是一个重载的方法,第一个参数为要复制的数组,第二个参数系数组的长度


public static int[] copyOf(int[] original, int newLength)



案例

 

        int[] arr = {1,2,3,4,5,6,7};
        int[] arr2 = Arrays.copyOf(arr,arr.length);
        System.out.println(Arrays.toString(arr2));


输出:


[1, 2, 3, 4, 5, 6, 7]
• 1


clone


通过源码可以看到该方法也是一个native方法,但其返回值为Object,因此赋值时会发生强转。其效率并不高


protected native Object clone() throws CloneNotSupportedException;



案例


int[] arr = {1,2,3,4,5,6,7};
        int[] arr3 = arr.clone();
        System.out.println(Arrays.toString(arr3));


输出:


[1, 2, 3, 4, 5, 6, 7]
• 1


在这四种方法中System.arraycopy是原生的,所以效率也是更高的。

相关文章
|
9月前
数组相关方法?
数组相关方法?
|
3月前
|
索引
数组的操作
`splice`方法改变原数组,如`arr.splice(a, b)`从下标`a`开始截取`b`个数。`push()`在数组尾部添加元素并返回新长度,`pop()`删除并返回尾部元素。`unshift()`在头部添加,`shift()`删除并返回头部元素。`findIndex()`返回满足条件的元素下标,否则-1。`forEach`遍历数组,`map`类似但返回新数组。
26 1
|
3月前
|
JavaScript 前端开发 索引
数组相关方法
数组相关方法
25 0
|
11月前
|
存储 Java 索引
Java数组长度和增强遍历数组
Java数组长度和增强遍历数组
47 0
数组去重-数组对象去重
数组去重-数组对象去重
40 0
|
9月前
|
前端开发
数组常用的几个方法
数组常用的几个方法
30 0
|
10月前
|
JSON C# 数据格式
数组比较的几种方式
1、string.Equals() ```csharp string[] strList1= new string[3] {"1", "2", "3"}; string[] strList2= new string[3] {"4", "5", "6"}; if (!string.Equals(strList1, strList2)) { // 比较数组的不同之处 } // 涉及到修改日志输出等数组可以直接json序列化然后用上述方法比较即可,如下 if (!string.Equals(JsonConvert.SerializeObject(list1), JsonConvert
60 0
|
12月前
数组的相关方法
数组的相关方法
33 0
|
Java API
最新Map遍历的5种方式
最新Map遍历的5种方式
100 0