본문

clone method

반응형

# clone method


이 메서드는 자신을 복제하여 새로운 인스턴스를 생성하는 일을 한다.
어떤 인스턴스에 대해 작업을 할 때, 원래의 인스턴스는 보존하고 clone메서드를 이용해서 새로운 인스턴스를 생성하여 작업을 하면,
작업이전의 값이 보존되므로 작업에 실패해서 원래의 상태로 되돌리거나 변경되기 전의 값을 참고하는데 도움이 될 것이다.


Source01) Point.java

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
36
package cloneMethod;
 
// Cloneable인터페이스를 구현한 클래스에서만 clone()을 호출할 수 있다. 
// 이 인터페이스를 구현하지 않고 clone()을 호출하면 예외가 발생한다.
class Point implements Cloneable {
    int x;
    int y;
 
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
 
    public String toString() {
        return "x= " + x + ", y= " + y;
    }
 
    public Object clone() {
        Object obj = null;
        try {
            // clone메서드에는 CloneNotSupportedException이 선언되어 있으므로 이 메서드를 호출할 때는
            // try-catch문을 사용해야한다.
            obj = super.clone();
        } catch (CloneNotSupportedException e) {}
        return obj;
    }
}
 
public class CloneEx01 {
    public static void main(String[] args) {
        Point original = new Point(35);
        Point copy = (Point)original.clone();    // 복제(clone)해서 새로운 객체를 생성
        System.out.println(original);
        System.out.println(copy);
    }
}
cs


Result)

1
2
x= 3, y= 5
x= 3, y= 5
cs

Object클래스에 정의된 clone메서드는 접근 제어자가 protected이므로, 

접근 제어자를 public으로 바꾸고, 조상인 Object클래스의 clone메서드를 통해 인스턴스를 복제하도록 오버라이딩했다.




- 배열 복사

일반적으로는 배열을 복사할 때, 같은 크기의 새로운 배열을 생성한 다음에 System.arraycopy()를 이용해서 내용을 복사하지만, 
이처럼 clone()을 이용해서 간단하게 복사할 수 있다는 것도 참고로 알아두자.

방법01)
int[] arr = {1,2,3,4,5};
int[] arrClone = arr.clone();


방법02)

int[] arr = {1,2,3,4,5};

int[] arrClone = new int[arr.length];                        // 배열을 생성하고

System.arraycopy(arr, 0, arrClone, 0, arr.length);        // 배열을 복사한다.


Source01) CloneEx02.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package cloneMethod;
 
import java.util.Arrays;
 
public class CloneEx02 {
    public static void main(String[] args) {
        int[] arr = { 12345 };
 
        // 배열 arr을 복제해서 같은 내용의 새로운 배열을 만든다.
        int[] arrClone = arr.clone();
        arrClone[0= 6;
 
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arrClone));
    }
}
cs


Result)

1
2
[12345]
[62345]
cs



배열 뿐 아니라 java.util패키지의 Vertor, ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, Calendar, Date와 같은 클래스들이 이와 같은 방식으로 복제가 가능하다.


1
2
3
Vector v = new Vector();
...
Vector v2 = (Vector)v.clone();
cs





출처 및 참고자료 : JAVA의정석(남궁성 저)

반응형

공유

댓글