방어적 복사
- 해야하는 이유 : getter 등을 통해 객체를 반환할 때 외부에서 해당 객체를 변경할 수 없도록 규제해야한다.
- Collections.unmodifiableList(해당 리스트)
- 읽기용도로만 사용하도록 제한한다.
- 원본에 변동이 가해질 경우 함께 변동
- new
- 아예 새로운 객체를 선언함으로써 원본과의 주소공유를 끊는다.
- 원본에 변동이 가해지더라도 영향이 없다.
- copyOf
- 참조값을 새롭게 생성함으로써 원본과의 주소공유를 끊고, 읽기용도로만 사용하도록 제한한다.
- 원본에 변동이 가해지더라도 영향이 없다.
- 그렇다면 이 방법들은 완전한 불변을 보장할까? NO. 참조값을 끊어내거나, 읽기제한만을 했을 뿐 객체 내부 요소 각각의 참조값은 그대로 가지고 있다. 즉, 객체 내부의 요소가 직접 변경된 경우 함께 변경이 일어난다.
- 어떻게하면 완전한 불변을 보장할 수 있을까? 깊은 복사를 진행한다. 해당 객체 자체 뿐만 아니라 내부 요소까지 전부 복사한다. 이를 지원하는 API는 없다 반복문 등을 활용하여 직접 해야한다.
- 항상 깊은 복사를 해야할까? NO. 객체가 변하지 않도록 잘 설계했다면, 충분히 안전하다 판단된다면 굳이 할 필요는 없다.
https://github.com/ulimy/2022-lv2-effective-java-interview/blob/main/ari/item_50.md