复制数组的几种方式

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

遍历复制

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

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是原生的,所以效率也是更高的。

相关文章
|
存储 人工智能 编译器
6.数组
6.数组
83 0
|
机器学习/深度学习 人工智能 算法
数组移动
给定一个数组a1,a2,a3,...an,b1,b2,b3..bn,最终把它置换成a1,b1,a2,b2,...an,bn。 分析: 本题是完美洗牌问题的变形。
882 0
|
9月前
数组练习2
数组练习2。
36 2
数组常用需求
数组常用需求
104 1
|
存储 C语言 索引
C 数组
C 数组。
55 0
|
8月前
数组(3)
数组(3)
44 2
|
存储 程序员 C#
【总结】C#中的数组
【总结】C#中的数组
|
9月前
|
存储 搜索推荐 程序员
C++ 数组
C++ 数组
61 0
|
4月前
|
存储 索引
数组的特点
数组是一种线性数据结构,用于存储固定大小的顺序集合。每个元素在数组中都有一个唯一的索引,可以快速访问和修改。数组支持随机访问,但插入和删除操作较慢,因为需要移动后续元素。适用于需要频繁读取数据的场景。

热门文章

最新文章