Java数组复制的三个方法
方法一,使用循环语句进行复制
public class ArrayCopyMethod {
public static void main(String[] args) {
int[] array1 = { 1, 2, 3, 4, 5, 6 };
int[] array2 = new int[array1.length];
// 使用循环语句进行数组的复制
for (int i = 0; i < array1.length; i++) {
array2[i] = array1[i];
}
System.out.println("复制后的数组array2:");
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
}
}
方法二,使用clone()方法
Object类是所有类的父类,其clone()方法一般用于创建并返回此对象的一个副本
public class ArrayCopyMethod {
public static void main(String[] args) {
int[] array1 = { 1, 2, 3, 4, 5, 6 };
int[] array2 = new int[array1.length];
// 使用循环语句进行数组的复制
for (int i = 0; i < array1.length; i++) {
array2[i] = array1[i];
}
// Object类是所有类的父类,其clone()方法一般用于创建并返回此对象的一个副本
int[] array3 = array1.clone();
System.out.println("复制后的数组array3:");
for (int i = 0; i < array3.length; i++) {
System.out.println(array3[i]);
}
}
}
方法三,使用System.arraycopy()方法
arraycopy()方法是System类的一个静态方法,可以实现数组拷贝功能
System.arraycopy(int from, int fromIndex, int to, int toIndex, int count)将数组from中的索引为fromIndex开始的元素拷贝到数组to中索引为toIndex的位置,总共拷贝的元素个数为count个
public class ArrayCopyMethod {
public static void main(String[] args) {
int[] array1 = { 1, 2, 3, 4, 5, 6 };
int[] array2 = new int[array1.length];
// 使用循环语句进行数组的复制
for (int i = 0; i < array1.length; i++) {
array2[i] = array1[i];
}
// Object类是所有类的父类,其clone()方法一般用于创建并返回此对象的一个副本
int[] array3 = array1.clone();
/*
* System.arraycopy(int from, int fromIndex, int to, int toIndex, int count)
* 将数组from中的索引为fromIndex开始的元素拷贝到数组to中索引为toIndex的位置,总共拷贝的元素个数为count个
*/
int[] array4 = new int[array1.length];
System.arraycopy(array1, 0, array4, 0, array1.length);
System.out.println("复制后的数组array4:");
for (int i = 0; i < array4.length; i++) {
System.out.println(array4[i]);
}
}
}