상식닷컴
로그인
가입하기
2026년 상식닷컴 선정 식당 & 카페 리스트
2025년 2026년 신상 호텔 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요
일주일 식단표 어플
자동 일주일 식단표 어플
안드로이드
아이폰
주식 & 코인 차트의 신
1000만원으로 2000만원 만들기 프로젝트
수정하기 - 자바에서 객체 복사 방법은 무엇인가요?
닉네임
비밀번호
제목
내용
[이미지 업로드는 권한이 있는 사람만 가능. 하단 카톡으로 연락]
<a href='https://sangseek.com/sangseeks/자바/ko'>자바</a>에서 객체 복사는 여러 가지 방법으로 수행할 수 있으며, 각 방법은 특정 상황에 따라 장단점이 있습니다. 객체 복사는 일반적으로 '얕은 복사(Shallow Copy)'와 '깊은 복사(Deep Copy)'로 나눌 수 있습니다. 이 두 가지 방법을 통해 객체를 복사하는 방법을 자세히 살펴보겠습니다. 1. 얕은 복사 (Shallow Copy)얕은 복사는 객체의 필드 값을 복사하지만, 객체가 참조하고 있는 다른 객체는 복사하지 않습니다. 즉, 원본 객체와 복사된 객체가 동일한 참조를 공유하게 됩니다. 얕은 복사는 주로 `clone()` 메서드를 오버라이드하여 구현합니다. 예제 코드```javaclass Person implements Cloneable { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }}public class Main { public static void main(String[] args) { try { Person original = new Person("Alice", 30); Person copy = (Person) original.clone(); System.out.println("Original: " + original.name + ", Age: " + original.age); System.out.println("Copy: " + copy.name + ", Age: " + copy.age); } catch (CloneNotSupportedException e) { e.printStackTrace(); } }}```이 예제에서 `Person` 클래스는 `Cloneable` 인터페이스를 구현하고 `clone()` 메서드를 오버라이드하여 얕은 복사를 수행합니다. `original` 객체를 복사하여 `copy` 객체를 생성합니다. 이 경우, `name`과 `age` 필드는 복사되지만, 만약 `Person` 클래스가 다른 객체를 참조하는 필드를 가졌다면, 그 참조는 공유됩니다. 2. 깊은 복사 (Deep Copy)깊은 복사는 객체와 그 객체가 참조하는 모든 객체를 재귀적으로 복사합니다. 따라서 원본 객체와 복사된 객체는 서로 독립적입니다. 깊은 복사를 구현하는 방법은 여러 가지가 있으며, 일반적으로 다음과 같은 방법을 사용합니다. 2.1. 수동으로 깊은 복사 구현각 필드에 대해 새로운 인스턴스를 생성하여 깊은 복사를 구현할 수 있습니다.```javaclass Address { String city; public Address(String city) { this.city = city; }}class Person { String name; int age; Address <a href='https://sangseek.com/sangseeks/address/ko'>address</a>; public Person(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } public Person deepCopy() { return new Person(this.name, this.age, new Address(this.address.city)); }}public class Main { public static void main(String[] args) { Address address = new Address("New York"); Person original = new Person("Alice", 30, address); Person copy = original.deepCopy(); System.out.println("Original Address: " + original.address.city); System.out.println("Copy Address: " + copy.address.city); // Modify the copy's address copy.address.city = "Los Angeles"; System.out.println("After modification:"); System.out.println("Original Address: " + original.address.city); System.out.println("Copy Address: " + copy.address.city); }}```이 예제에서 `Person` 클래스는 `deepCopy()` 메서드를 통해 깊은 복사를 구현합니다. `Address` 객체도 새로 생성하여 복사하므로, `original`과 `copy`는 서로 독립적으로 존재합니다. 2.2. <a href='https://sangseek.com/sangseeks/직렬화/ko'>직렬화</a>(<a href='https://sangseek.com/sangseeks/Serialization/ko'>Serialization</a>) 사용자바의 직렬화 기능을 사용하여 객체를 깊은 복사할 수도 있습니다. 이 방법은 객체를 바이트 스트림으로 변환한 후 다시 객체로 변환하는 방식입니다. 이 방법을 사용하려면 클래스가 `Serializable` 인터페이스를 구현해야 합니다.```javaimport java.io.*;class Address implements Serializable { String city; public Address(String city) { this.city = city; }}class Person implements Serializable { String name; int age; Address address; public Person(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } public Person deepCopy() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (Person) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); return null; } }}public class Main { public static void main(String[] args) { Address address = new Address("New York"); Person original = new Person("Alice", 30, address); Person copy = original.deepCopy(); System.out.println("Original Address: " + original.address.city); System.out.println("Copy Address: " + copy.address.city); // Modify the copy's address copy.address.city = "Los Angeles"; System.out.println("After modification:"); System.out.println("Original Address: " + original.address.city); System.out.println("Copy Address: " + copy.address.city); }}```이 방법은 객체의 모든 필드가 직렬화 가능할 때 유용하며, 복잡한 <a href='https://sangseek.com/sangseeks/객체 구조/ko'>객체 구조</a>를 쉽게 복사할 수 있습니다. 그러나 성능이 떨어질 수 있으며, 직렬화가 불가능한 객체가 포함된 경우 예외가 발생할 수 있습니다. 결론자바에서 객체 복사는 얕은 복사와 깊은 복사의 두 가지 방법으로 수행할 수 있습니다. 얕은 복사는 간단하고 빠르지만, 참조하는 객체가 변경되면 원본 객체에도 영향을 미칠 수 있습니다. 깊은 복사는 더 복잡하지만, 객체 간의 독립성을 유지할 수 있습니다. 각 방법의 장단점을 고려하여 상황에 맞는 복사 방법을 선택하는 것이 중요합니다.
이용안내
커뮤니티 이용안내
×
- 게시한 게시글로 발생하는 문제는 게시자에게 책임이 있습니다.
- 게시글이 타인/타업체의 저작권을 침해할 경우 모든 책임은 게시자에게 있습니다. 게시자가 모든 손해를 부담해야 합니다.
- 상식닷컴 운영자는 게시자와 상의하지 않고 게시글을 수정 또는 삭제할 수 있습니다.
- 상식닷컴 운영자는 깨끗한 커뮤니티 공간을 만드는 것이 1순위입니다.
수정하기
취소하기