[Java] Shallow Copy和Deep Copy

前言

在複製陣列的時候,要注意是需要Shallow Copy還是Deep Copy,直接看程式碼。

Shallow Copy

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
28
29
30
31
32
import java.util.*;
import java.io.*;
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
int a[] = {1,2,3,4,5} ;
int b[] = a ;
System.out.print("a = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(a[i]+" ") ;
System.out.println();
System.out.print("b = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(b[i]+" ") ;
System.out.println();
a[1] = 7 ;
System.out.print("a = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(a[i]+" ") ;
System.out.println();
System.out.print("b = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(b[i]+" ") ;
System.out.println();
}
}

可以看到當a改變的時候b也跟著改變了,這是因為b是reference到a陣列,但如果要個別獨立就必須使用Deep Copy

Deep Copy

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
28
29
30
31
32
33
34
35
import java.util.*;
import java.io.*;
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
int a[] = {1,2,3,4,5} ;
int b[] = new int[a.length] ;
for ( int i = 0 ; i < a.length ; i ++ )
b[i] = a[i] ;
System.out.print("a = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(a[i]+" ") ;
System.out.println();
System.out.print("b = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(b[i]+" ") ;
System.out.println();
a[1] = 7 ;
System.out.print("a = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(a[i]+" ") ;
System.out.println();
System.out.print("b = ");
for ( int i = 0 ; i < a.length ; i ++ )
System.out.print(b[i]+" ") ;
System.out.println();
}
}

簡單來說就是先配置記憶體位置給b,再將a的內容逐項複製過去。