개발/java

불변객체 만들기 ImmutableCollections.class

방푸린 2024. 9. 14. 15:55
반응형
class ImmutableCollections {
  • Java 9 and Later: Provides factory methods (List.of, Set.of, Map.of) to create immutable collections.
    • List.of(...): Creates an immutable list.
    • Set.of(...): Creates an immutable set.
    • Map.of(...): Creates an immutable map.
  • Java 16: Enhances immutable collection creation with additional methods for more control.

 

특징

  • Thread-Safety: Immutable collections are inherently thread-safe because their state cannot change after construction.
  • No Modifications: Methods that modify the collection (like add, remove, put, etc.) throw UnsupportedOperationException.
  • Efficient: Immutable collections are often more memory-efficient and can be optimized by the JVM.

 

아래 함수가 호출되면 에러 발생! 추가 삭제 정렬 불가.

// all mutating methods throw UnsupportedOperationException
@Override public void    add(int index, E element) { throw uoe(); }
@Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); }
@Override public E       remove(int index) { throw uoe(); }
@Override public void    replaceAll(UnaryOperator<E> operator) { throw uoe(); }
@Override public E       set(int index, E element) { throw uoe(); }
@Override public void    sort(Comparator<? super E> c) { throw uoe(); }

 

 

참고로 리스트 콜랙션에도 불변객체를 바로 만들 수 있는데,, ImmutableCollections 함수와는 무관하지만 스트림에 추가된 기능이다.

toList() Method in Streams (Java 16 and Later)

  • Purpose: Collects the elements of a Stream into an immutable List.
  • Usage: Provides a convenient way to create an immutable list directly from a stream.

Collectors.toList() vs. toList()

  • Collectors.toList(): from java8, Creates a mutable list by default, which can be modified after collection. ArrayList
  • Stream.toList(): Introduced in Java 16, creates an immutable list directly from a stream, offering a more streamlined approach to get immutable results.
728x90
반응형