반응형
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
반응형
'개발 > java' 카테고리의 다른 글
Runnable vs Callable (0) | 2024.09.20 |
---|---|
[힙 덤프] 떠있는 프로세스 분석 (0) | 2024.09.19 |
[java] try with resources; close (1) | 2024.05.09 |
[java] 객체 소팅 시 비교하는 법 comparable, comparator (0) | 2024.05.08 |
[java] 멀티 스레드 동시성 관련 (0) | 2024.05.08 |