플랫 카피
얕은 복사는 참조 변수가 가리키는 객체의 주소만 복사하고 새 객체 자체를 생성하지 않습니다. 이렇게 하면 원래 개체와 복사된 개체가 모두 동일한 개체를 참조하고 원래 개체나 복사된 개체 중 하나가 개체의 내용을 변경하면 다른 개체도 변경됩니다.
예) 플랫카피
public class Person {
private String name;
private int age;
}
Person person1 = new Person();
person1.setName("Alice");
person1.setAge(20);
Person person2 = person1; // 얕은 복사
person2.setName("Bob");
System.out.println(person1.getName()); // 출력: Bob
위의 코드에서 person2의 변수는 person1의 변수와 동일한 객체를 참조합니다. 따라서 Person2 개체의 Name 속성을 변경하면 Person1 개체의 Name 속성도 변경됩니다. 이미 언급했듯이 얕은 복사 예 생산하는인스턴스화될 때 메모리에 할당됨 주소 값얕은 복사는 복사된 개체가 원본 개체와 동일함을 의미하기도 합니다. 매달린오전.
– 플랫 카피는 참조별 참조와 유사한 개념인 주소별 참조입니다.
깊은 복사
복사할 원본 객체에 대한 새로운 단일 객체 또는 복합 객체를 생성하고 원본과 관계없이 원본 객체로 인스턴스화할 수 있는 클래스 내 클래스 변수(정적) 및 메서드(정적)는 물론 모든 인스턴스 값을 복사합니다. object 객체 생성, 즉 (call-by values)
예) 깊은 복사
Person person1 = new Person();
person1.setName("Alice");
person1.setAge(20);
Person person2 = new Person();
person2.setName(person1.getName());
person2.setAge(person1.getAge());
person2.setName("Bob");
System.out.println(person1.getName()); // 출력: Alice
//실제로 person2가 deep copy되었는지 확인하려면?
//person1과 person2의 메모리 주소를 확인하면 된다. 얕은 복사라면 같은 주소를 사용할 것이다.
System.out.println(person1.hashCode());
System.out.println(person2.hashCode());

