- collection-복사2025년 01월 11일
- BE_규원
- 작성자
- 2025.01.11.:49
방어적 복사
객체의 복사본을 만들어서 반환하는 방법이며
복사본을 수정해도 원본이 수정되지 않아야 한다
얕은 복사
복사본을 만들 때, 새로운 객체를 만들고 원본의 주소 값을 참조하는 방법이며
원본과 복사본은 동일한 주소 값을 가리키고 있다
깊은 복사
복사본을 만들 때, 새로운 객체를 만들고 모든 값을 복사해오는 방법이며
원본과 복사본은 서로 다른 객체를 가리키며 서로 동일한 값을 가지고 있다
복사 방법 5 가지
- 원본 collection 그대로 getter 를 통해 반환하기
- new 를 통해 새로운 Collection 생성해 반환하기
- Collection.unmodifiableList() 를 통해 Collection 반환하기
- List.copyOf() 를 통해 Collection 반환하기
- 복사 생성자 + Collections.unmodifiableList 를 통해 Collection 반환하기
원본 collection 그대로 getter 를 통해 반환하기
public class Cars { private final List<Car> cars; public Cars(final List<Car> cars) { this.cars = cars; } public List<Car> getCars() { return cars; } }
원본을 그대로 전달하게 된다
방어적 복사가 아니며, 얕은 복사 방법이다
new 를 통해 Collection 생성해 반환하기
public class Cars { private final List<Car> cars; public Cars(final List<Car> cars) { this.cars = cars; } public List<Car> getCars() { return new ArrayList<>(cars); } }
Collection.unmodifiableList() 를 통해 Collection 반환하기
public class Cars { private final List<Car> cars; public Cars(final List<Car> cars) { this.cars = cars; } public List<Car> getCars() { return Collections.unmodifiableList(cars); } }
List.copyOf() 를 통해 Collection 반환하기
public class Cars { private final List<Car> cars; public Cars(final List<Car> cars) { this.cars = cars; } public List<Car> getCars() { return List.copyOf(cars); } }
복사 생성자 + Collections.unmodifiableList 를 통해 Collection 반환하기
public class Car { private String name; private int position; public Car(String name, int position) { this.name = name; this.position = position; } // 복사 생성자 public Car(Car car) { this.name = car.name; this.position = car.position; } }
public class Cars { private final List<Car> cars; public Cars(final List<Car> cars) { this.cars = cars; } public List<Car> getCars() { return cars.stream() .map(Car::new) // 복사 생성자로 Car 생성 .collect(Collectors.toUnmodifiableList()); } }
'back-end' 카테고리의 다른 글
영속성-컨텍스트? entity-manager? (0) 2025.01.08 tomcat-netty (1) 2025.01.04 effective-java-4 (0) 2025.01.01 effective-java-3 (0) 2025.01.01 effective-java-2 (0) 2025.01.01 다음글이전글이전 글이 없습니다.댓글
스킨 업데이트 안내
현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)