본문 바로가기
언어/JAVA

[JAVA] 깊은 복사와 얕은 복사

by 코딩맛집 2024. 1. 2.

1차원 배열 복사

 

얕은 복사란?

- 객체의 주소 값을 복사하는 것이다.
- 여러 객체가 같은 주소를 참조하기 때문에 하나의 값을 변경하면 다른 대상의 값도 변경된다.
- 한 개의 객체 주소를 참조하므로 하나의 객체라고 볼 수 있다.
- 하나의 객체로써 사용이 가능하다면 쓸데없이 객체를 복사하여 사용할 필요없지만 이럴 경우 사용한다는 의미가 된다.

public class Array_Copy{
    public static void main(String[] args)  {
        int[] a = { 1, 2, 3, 4 };
        int[] b = a;
    }
}

 

 

깊은 복사란?

- 객체의 실제 값을 새로운 객체로 복사하는 것이다.
- 다른 주소와 같은 값인 객체가 두개 존재하게 된다.
- 대개 객체를 복사한다는 말은 얕은 복사가 아닌 깊은 복사를 의미한다. 

public class Array_Copy{
    public static void main(String[] args)  {
        int[] a = { 1, 2, 3, 4 };
        int[] b = new int[a.length]; 
        for (int i = 0; i < a.length; i++) {
            b[i] = a[i];
        }
    }
}

 

배열을 복사하는 여러가지 메서드(깊은 복사)

1. clone()

public class Array_Copy{
    public static void main(String[] args)  {
        int[] a = { 1, 2, 3, 4 };
        int[] b = a.clone();
    }
}

 

2. Arrays.copyOf()

import java.util.Arrays;

public class Array_Copy{
    public static void main(String[] args)  {
        int[] a = { 1, 2, 3, 4 };
        int[] b = Arrays.copyOf(a, a.length);
    }
}

 Arrays.copyOf(배열 변수, 복사하려는 길이)

 

3. Arrays.copyOfRange()

import java.util.Arrays;

public class Array_Copy{
    public static void main(String[] args)  {
        int[] a = { 1, 2, 3, 4 };
        int[] b = Arrays.copyOfRange(a, 1, 3);
    }
}

 Arrays.copyOf(배열 변수, 시작 인덱스, 종료 인덱스)

종료 인덱스는 포함 x

 

4. System.arraycopy()

public class Array_Copy{
    public static void main(String[] args)  {
        int[] a = { 1, 2, 3, 4 };
        int[] b = new int[a.length];
        System.arraycopy(a, 0, b, 0, a.length);
    }
}

System.arraycopy(원본 배열, 원본 배열의 시작 인덱스, 복사하려는 배열, 복사 배열의 시작 인덱스, 복사하려는 길이)

 

 

2차원 배열 복사

2차원 배열의 경우 위의 메서드로 깊은 복사가 되지 않는다.

그 이유는 2차원 배열의 구조 a[x][y]에서 배열을 복사하는 메서드를 사용하면 y좌료를 가리키는 주소 값 a[x] 부분만 깊은 복사가 되고 값이 존재하는 a[x][y]는 깊은 복사가 되지 않습니다.

 

그렇다면 2차원 배열을 복사하기 위해서는 어떤 방법이 있을까요?

 

1. 2중 for문 활용

public class Array_Copy{
    public static void main(String[] args)  {
        int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
        int[][] b = new int[a.length][a[0].length];
	    
        for(int i=0; i<a.length; i++) {
            for(int j=0; j<a[i].length; j++) {
                b[i][j] = a[i][j];  
            }
        }
    }
}

 

2. System.arraycopy()

public class Array_Copy{
    public static void main(String[] args)  {
        int a[][] = {{1,2,3},{4,5,6,},{7,8,9}};
        int b[][] = new int[a.length][a[0].length];
	    
        for(int i=0; i<b.length; i++){
            System.arraycopy(a[i], 0, b[i], 0, a[0].length);
        }
    }
}

 

 

※ 공부용입니다.

 

참조 : https://coding-factory.tistory.com/548

'언어 > JAVA' 카테고리의 다른 글

[JAVA] substring()  (1) 2024.01.04
[JAVA] startsWith() 와 endsWith()  (1) 2024.01.04
[Java] 배열을 문자열로 변환  (0) 2023.05.02
String.valueOf()과 Object.toString() 차이점  (0) 2023.05.02
StringTokenizer  (0) 2023.04.02