[Java] List 불변 객체, 가변 객체

jipyo park·2022년 10월 30일
0

java

목록 보기
5/5

불변 객체, 가변 객체에 대한 기본 개념!!

Java List에서의 객체는??

일단 List라는 자료구조는 자체는 가변 객체라고 볼수있다.
List안에 있는 add와, remove, set을 통해 내부 데이터가 변경이 될 수 있기 때문이다.

public class Main {
	public static void main(String[] args) {
    	List<String> list = new ArrayList<>();
        list.add("Hello");
        // ["Hello"]
        list.set(0, "world");
        // ["world"]
        list.remove(0);
        // []
    }
}

근데 List라는 자료구조에서 불변객체라니...??
public class Main {
	public static void main(String[] args) {
    	List<String> list = List.of("Hello", "World");
    }
}

이렇게 List.of()를 쓰게 되면 데이터의 변경이 불가능하고 데이터 탐색만 가능해진다.

add, set, remove 등 내부 데이터를 변경하려고 하면 UnsupportOperationException가 뜨게 된다.

이 List.of() 메서드는 내부적으로 AbstractImmutableList를 반환한다.

이 클래스에서는 add, addAll, remove, replaceAll, set, sort 메서드를 실행하면 UnsupportOperationException예외가 발생하도록 설계되었다.

데이터 변경을 일으키는 메서드를 호출하면 UOE 예외를 발생시켜 내부 데이터 변경을 막았고, 결과적으로 불변 객체가 생성 되었다고 말할 수 있다.

List.of()와 같이 다른 컬렉션 프레임워크인 Map와 Set에서도 of() 메서드를 사용하여 불변 객체를 만들 수 있다.

5개의 댓글

comment-user-thumbnail
2023년 9월 20일

Just like any other part of your home, swimming pools can benefit from a facelift. Over the years, pool surfaces may become stained, cracked, or swimming pool repair service diminishing their visual appeal. Renovation can breathe new life into your pool, giving it a fresh and inviting look.

답글 달기
comment-user-thumbnail
2023년 9월 20일

When it comes to combining style and functionality, nothing beats a genuine thefinestleathers.com leather jacket. It's an iconic piece that not only keeps you warm but also adds a touch of timeless elegance to your ensemble.

답글 달기
comment-user-thumbnail
2023년 9월 20일

Apartments takes pride in offering flexible lease options tailored to meet the diverse needs of our residents. Every student has a unique Student housing situation, whether you're seeking a short-term or long-term lease.

답글 달기
comment-user-thumbnail
알 수 없음
2023년 10월 16일
수정삭제

삭제된 댓글입니다.

1개의 답글
comment-user-thumbnail
2023년 11월 29일

Compared to traditional outbound marketing methods, pervasivemarketing.com is often more cost effective. Agencies can optimize digital advertising spend focusing on high-impact strategies that resonate with the target audience.

답글 달기