๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/JAVA

[JAVA] ๊ฐ์ฒด ๋ณต์ œ(clone)์™€ Shallow Copy, Deep Copy

by ynzu๐Ÿค 2022. 2. 16.
๋ฐ˜์‘ํ˜•

 

๊ฐ์ฒด๋ฅผ ๋ณต์ œํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” Cloneable์„ ๊ตฌํ˜„ํ•˜๊ณ , clone() ๋ฉ”์†Œ๋“œ๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œํ•˜๋ฉด ๋˜์„œ ๊ฐ„๋‹จํ•˜๋‹ค!

@Getter
@Setter
public class Person implements Cloneable{
	
	private String name;
	
	private int age;
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

}

 

๊ทธ๋ฆฌ๊ณ  ์•„๋ž˜์™€ ๊ฐ™์ด person1.clone(); ์„ ์‚ฌ์šฉํ•˜์—ฌ person1์˜ ๊ฐ์ฒด๋ฅผ ๋ณต์ œํ•˜์˜€๋‹ค.

Person person1 = new Person();
person1.setName("ํ™๊ธธ๋™");
person1.setAge(30);
		
try {
    Person person2 = (Person)person1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}

clone()์œผ๋กœ ๊ฐ์ฒด๋ฅผ ๋ณต์ œํ•˜๋Š” ๊ฒƒ์€ Deep Copy(๊นŠ์€ ๋ณต์ œ)๋กœ ์ƒˆ๋กœ์šด ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์— ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค.

์ฆ‰, ์„œ๋กœ ๋‹ค๋ฅธ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์›๋ณธ์„ ๋ณ€๊ฒฝํ•ด๋„ ๋ณต์ œ๋ณธ์ด ์˜ํ–ฅ์„ ๋ฐ›์ง€ ์•Š๋Š”๋‹ค. 

 


์ž๋ฐ”์—์„  Shallow Copy์™€ Deep Copy๊ฐ€ ์žˆ๋Š”๋ฐ ๊ทธ ์ฐจ์ด๊ฐ€ ๋ญ”์ง€ ์•Œ์•„๋ณด์ž.

Shallow Copy(์–•์€ ๋ณต์ œ)๋Š” ์›๋ณธ๊ณผ ๋ณต์ œ๋ณธ์ด ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ๊ณต์œ ํ•˜๋ฏ€๋กœ ์™„์ „ํ•œ ๋ณต์ œ๋ผ ๋ณด๊ธฐ ์–ด๋ ต๋‹ค. (= ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ)

์ฆ‰, ๊ฐ’์ด ์•„๋‹Œ ์ฃผ์†Œ๊ฐ’์„ ๋ณต์‚ฌํ•˜๊ณ , ์›๋ณธ์„ ๋ณ€๊ฒฝํ•˜๊ฒŒ ๋˜๋ฉด ๋ณต์ œ๋ณธ๋„ ์˜ํ–ฅ์„ ๋ฐ›๊ฒŒ ๋œ๋‹ค.

 

์•„๋ž˜ ์˜ˆ์ œ๋ฅผ ์‚ดํŽด๋ณด๋ฉด Shallow Copyํ•œ person3๋Š” person1์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋˜๋‹ˆ ์˜ํ–ฅ์„ ๋ฐ›์•˜๊ณ , Deep Copyํ•œ person2๋Š” ์˜ํ–ฅ์„ ๋ฐ›์ง€ ์•Š์€ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

Person person1 = new Person();
person1.setName("ํ™๊ธธ๋™");
person1.setAge(30);

Person person2 = null;
try {
	//Deep Copy
	person2 = (Person)person1.clone();
} catch (CloneNotSupportedException e) {
	e.printStackTrace();
}

//Shallow Copy
Person person3 = person1;

System.out.println(person1.getName()); //ํ™๊ธธ๋™
System.out.println(person2.getName()); //ํ™๊ธธ๋™
System.out.println(person3.getName()); //ํ™๊ธธ๋™

//person1์˜ ์ด๋ฆ„ ๋ณ€๊ฒฝ
person1.setName("์•„๋ฌด๊ฐœ");

System.out.println(person1.getName()); //์•„๋ฌด๊ฐœ
System.out.println(person2.getName()); //ํ™๊ธธ๋™
System.out.println(person3.getName()); //์•„๋ฌด๊ฐœ

 

 

๊ทธ๋ฆฌ๊ณ  ๊ฐ ๊ฐ์ฒด์˜ ํ•ด์‹œ์ฝ”๋“œ๋ฅผ ์ถœ๋ ฅํ•ด๋ณด๋ฉด person1๊ณผ person3๋Š” ๋™์ผํ•œ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

System.out.println(person1.hashCode()); //903470137
System.out.println(person2.hashCode()); //1913208269
System.out.println(person3.hashCode()); //903470137

 

๋ณธ์ธ์€ ํ™˜๊ฒฝ์„ค์ • ์ •๋ณด๋ฅผ ๋‹ด์€ ๊ฐ์ฒด์˜ ๋ณ€๊ฒฝ์„ ๋ง‰๊ณ ์ž ํ•ด๋‹น ๊ฐ์ฒด๋ฅผ ๋„˜๊ธธ๋•Œ Deep Copy(clone)์„ ์ด์šฉํ•˜์—ฌ ๋ณต์ œ๋œ ๊ฐ์ฒด๋ฅผ ๋„˜๊ฒผ๊ณ , ์›๋ณธ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๋„๋ก ํ•˜์˜€๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€