back-end
collection-복사
BE_규원
2025. 1. 11. 14: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());
}
}