Copy
Shallow Copy vs Deep Copy
์์ ๋ณต์ฌ Shallow Copy
์ฃผ์๋ฅผ ๋ณต์ฌํฉ๋๋ค.
ํ์ชฝ์ ์์ ์ด ์ด๋ฃจ์ด์ง๋ฉด ๋ค๋ฅธ ํ ์ชฝ์๋ ์ํฅ์ด ๊ฐ๋๋ค.
๊น์ ๋ณต์ฌ Deep Copy
์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑ ํฉ๋๋ค.
์๋ก ๊ฐ ์ํฅ์ด ์์ต๋๋ค.
Java ์์ ์ฌ์ฉ๋๋ Copy ๋ฉ์๋์ ๋น๊ต
System.arraycopy()
Deep
Shallow
Fastest
Object.clone()
Deep
Shallow
Fast
Arrays.copyOf()
Deep
Shallow
Fast
Using for
Depend on code
Depend on code
Slow
Primitive Type ์ ๊ฐ ๊ทธ ์์ฒด์ด๊ธฐ ๋๋ฌธ์ Deep Copy ๋ฅผ ์ง์ํฉ๋๋ค.
Non-Primitive Type ์ ์ฃผ์๋ฅผ ๋ณต์ฌํ๋ฉฐ Swallow Copy ๋ฅผ ์ง์ํฉ๋๋ค.
clone()
clone() ์ shallow copy ๋ฅผ ์ง์ํฉ๋๋ค. deep copy ๋ฅผ ์ํด์๋ Cloneable ๋ฅผ ๊ตฌํํ๊ฑฐ๋ ํด์ฃผ๊ฑฐ๋ new ๋ฅผ ํตํด deep copy ๋ฅผ ํด์ฃผ์ด์ผ ํฉ๋๋ค.
์ํ ์ฝ๋
Cloneable ๋ฅผ implements ํ์ง ์์ ์ฌ์ฉ์ ์ ์ ํด๋์ค
clone : shallow copy
forCopy : deep copy
import java.util.Arrays;
public class test {
public static class Temp {
public int a;
public Object obj;
public Temp(int a) {
this.a = a;
this.obj = new Object();
}
public int getA() {
return a;
}
}
public static void main(String[] args) {
Temp[] origin = new Temp[]{new Temp(1), new Temp(2), new Temp(280), new Temp(1500), new Temp(40000)};
Temp[] arrayCopy = new Temp[5];
System.arraycopy(origin, 0, arrayCopy, 0, 5);
Temp[] clone = origin.clone();
Temp[] copyOf = Arrays.copyOf(origin, 5);
Temp[] forCopy = new Temp[5];
for (int i = 0; i < origin.length; i++) {
forCopy[i] = new Temp(origin[i].getA());
}
}
}
Last updated
Was this helpful?