数组的复制

1、四种数组复制方式的逐一详细说明:
第一种方式利用for循环:
int[] a = {1,2,4,6};
int length = a.length;
int[] b = new int[length];
for (int i = 0; i < length; i++) {
  b[i] = a[i];
}

第二种方式直接赋值:
int[] array1 = {1,2,4,6};
int[] array2 = a;
这里把array1数组的值复制给array2,如果你这样去运行,就会发现此时两个数组的值是一样的。这是传递的是引用(也就是地址),之后改变其中一个数组另一个也会跟着变化。

第三种方式:
利用Arrays自带的copyof
int copy[] = Arrays.copyOf(a, a.length);

第四种方式:
利用System.arraycopy()这个函数,从JAVA API中找了一段,大家看一下。
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
参数说明:src     - the source array.  
            指源数组

     srcPos  - starting position in the source array.  
            指要复制的源数组的起始下标

     dest  - the destination array.  
            指目标数组

     destPos - starting position in the destination data.  
            指目标数组复制起始下标

     length  - the number of array elements to be copied. 
            指数组元素复制长度
 1 package test;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Test {
 6     public static void main(String[] args) {
 7         int[] source = {1,2,3,4,5};
 8         int[] dest = {10,9,8,7,6,5,4,3,2,1};
 9         
10         System.arraycopy(source,0,dest,2,3);
11         System.out.println(Arrays.toString(dest));
12     }
13 }
示例代码
1 [10, 9, 1, 2, 3, 5, 4, 3, 2, 1]
运行结果



2、四种方式之总结
第一种方式得到的两个数组是两个不同的对象,用“==”比较结果一定是false;但用equals()方法比较可以是true。
 1 package test;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Test {
 6   public static void main(String[] args) {
 7     int[] a = {1,2,4,6};
 8     int length = a.length;
 9     int[] b = new int[length];
10 
11     for (int i = 0; i < length; i++) {
12       b[i]=a[i];
13     }
14 
15   System.out.println(Arrays.toString(a));
16   System.out.println(Arrays.toString(b));
17 
18   System.out.println(a.toString());
19   System.out.println(b.toString());
20   System.out.println("a==b:"+(a == b));
21   System.out.println("Arrays.equals(a,b):"+Arrays.equals(a, b));
22   }
23 }
示例代码
1 [1, 2, 4, 6]
2 [1, 2, 4, 6]
3 [I@3654919e
4 [I@6a2437ef
5 a==b:false
6 Arrays.equals(a,b):true
运行结果

第二种方式得到的两个数组其实就是一个对象,无论用 “==”还是 equals() 方法比较,结果都是true。

第三种方式得到的两个数组是两个不同的对象。
第四种方式得到的两个数组也是两个不同的对象。
原文地址:https://www.cnblogs.com/Mike_Chang/p/6618599.html