본문 바로가기

개발/Java

Shallow copy와 Deep copy

Shallow copy

1. 객체를 복사할 때 해당 객체의 메모리 주소만 복사합니다.

2. 따라서 복사된 객체의 값이 변경되면 원본 객체의 값도 변경됩니다.

 

 

Deep Copy

1. 객체를 복사할 때 아예 새로운 객체를 만드는 개념입니다.

2. 따라서 복사한 객체의 값이 변경되도 원본 객체에 영향을 주지 않습니다.

추가적으로 Cloneable 인터페이스를 상속받아 clone() 메소드를 오버라이드하여 많이 사용했지만,,, Josuah Bloch님이 쓴 Effective Java 2nd Edition에서 이 방법을 추천하지 않는다고 합니다. 그래서 copy constructor를 사용한다고 하는데 아래의 코드가 copy constructor를 사용한 코드입니다.

 

public class CopyTest {
	public static void main(String[] args) {
		Person source = new Person("jaesuk", 50);

		//Shallow Copy
		Person copy = source;

		copy.setName("somin");

		System.out.println(source.getName());
		System.out.println(copy.getName());


		//Deep Copy
		Person newSource = new Person("gwangsoo", 35);

		Person newCopy   = new Person(newSource);

		newCopy.setName("sukjin");

		System.out.println(newSource.getName());
		System.out.println(newCopy.getName());
	}
}

class Person{
	private String name;
	private Integer age;

	public Person(String name, Integer age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return this.name;
	}
	public Integer getAge() {
		return this.age;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(Integer age) {
		this.age = age;
	}

	public Person(Person source) {
		this.name = source.getName();
		this.age = source.getAge();
	}

}

 

결과

'개발 > Java' 카테고리의 다른 글

jar vs war  (0) 2022.05.03
Import vs Import static  (0) 2021.06.17
암호화란? (ECB 샘플 코드)  (0) 2021.03.16
Java 배열 정렬  (0) 2021.02.22
Scanner vs BufferedReader 비교  (0) 2021.02.10