我是靠谱客的博主 坦率人生,这篇文章主要介绍java数组的几种复制方法,现在分享给大家,希望可以做个参考。

1、Arrays.copyOf

复制代码
1
dataType[] targetArray = Arrays.copyOf(dataType[] sourceArray,int length)

 其中sourceArray代表的是要进行复制的数组(源数组),length代表的是复制数组的长度。使用这个方法复制数组,默认的是从数组第一个元素开始复制。而length是目标数组的长度,如果length大于srcArray数组的长度,那么目标数组会采用默认值进行填充。如果length小于srcArray数组的长度,那么复制的时候只复制到length个元素为止。  如果目标数组里面有数据,源数组里面的数据就会覆盖目标数组的数据。

复制代码
1
2
3
4
5
int[] a1 = {1, 2, 3, 4, 5}; int[] a2 = Arrays.copyOf(a1, 3); System.out.println(Arrays.toString(a1)) // [1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2)) // [1, 2, 3]

2、Arrays.copyOfRange

复制代码
1
dataType[] targetArray = Arrays.copyOf(dataType[] sourceArray,int startPosition,int length)

其中sourceArray代表的是要进行复制的数组(源数组),startPosition代表开始复制的位置,length代表的是复制数组的长度。

3、clone

java.lang.Object类的clone()方法为protected类型,基本数据类型(String ,boolean,char,byte,short,float ,double,long)都可以直接使用clone方法进行克隆,注意String类型是因为其值不可变所以才可以使用。对象类型不可直接调用,需要先对要克隆的类进行下列操作:首先被克隆的类实现Cloneable接口,然后在该类中覆盖clone()方法,并且在该clone()方法中调用super.clone(),这样,super.clone()便可以调用java.lang.Object类的clone()方法。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//被克隆的类要实现Cloneable接口 class Student implements Cloneable { private String name; private int age; public Student (String name,int age) { this.name=name; this.age=age; } //重写clone()方法 protected Object clone()throws CloneNotSupportedException{ return super.clone() ; } } public class TestClone{ public static void main(String[] args) throws CloneNotSupportedException { Student student1=new Student("李三",18); System.out.println(student1); //调用clone方法 Student student2=(Student)student1.clone(); System.out.println(student2); } }

4、System.arraycopy

复制代码
1
public static native void arraycopy(Object src, int srcPos, Object dest, int desPos, int length)

其中src源数组,srcPos 源数组的开始位置, dest目标数组, desPos目标数组的开始位置, length拷贝个数。

复制代码
1
2
3
4
5
6
int[] a1 = {1, 2, 3, 4, 5}; int[] a2 = new int[10]; System.arraycopy(a1, 1, a2, 3, 3); System.out.println(Arrays.toString(a1)); // [1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2)); // [0, 0, 0, 2, 3, 4, 0, 0, 0, 0]

 

效率:System.arraycopy > clone > Arrays.copyOf 

 

 

 

 

 

 

最后

以上就是坦率人生最近收集整理的关于java数组的几种复制方法的全部内容,更多相关java数组内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部