Language/JAVA

[JAVA] 수정할 수 없는 컬렉션

IT수정 2024. 10. 18. 11:34

수정할 수 없는 컬렉션

수정할 수 없는 컬렉션이란 요소를 추가, 삭제할 수 없는 컬렉션을 말한다. 컬렉션 생성 시 저장된 요소를 변경하고 싶지 않을 때 유용하다. 여러 가지 방법으로 만들 수 있는데, 먼저 첫 번째 방법으로는 List, Set, Map 인터페이스의 정적 메서드인 of()로 생성할 수 있다.

List<E> immutableList = List.of(E... elements);
Set<E> immutableSet = Set.of(E... elements);
Map<K, V> immutableMap = Map.of(K k1, V v1, K k2, V v2, ...);

 

두 번째 방법은 List, Set, Map 인터페이스의 정적메서드인 copyOf()을 이용해 기존 컬렉션을 복사하여 수정할 수 없는 컬렉션을 만드는 것이다.

List<E> immutableList = List.copyOf(Collection<E> coll);
Set<E> immutableSet = Set.copyOf(Collection<E> coll);
Map<K, V> immutableMap = Map.copyOf(Map<K, V> map);

 

세 번째 방법은 배열로부터 수정할 수 없는 List 컬렉션을 만들 수 있다.

String[] arr = { "A", "B", "C" };
List<String> immutableList = Arrays.asList(arr);

 

예제 코드

package ch15;

import java.util.*;

public class ImmutableExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String> immutableList1 = List.of("A", "B", "C");
		
		Set<String> immutableSet1 = Set.of("A", "B", "C");
		
		Map<Integer, String> immutableMap1 = Map.of(1, "A", 2, "B", 3, "C");
		
		List<String> list = new ArrayList<>();
		list.add("A");
		list.add("B");
		list.add("C");
		List<String> immutableList2= List.copyOf(list);
		
		Set<String> set = new HashSet<>();
		set.add("A");
		set.add("B");
		set.add("C");
		Set<String> immutableSet2 = Set.copyOf(set);
		
		Map<Integer, String> map = new HashMap<>();
		map.put(1, "A");
		map.put(2, "B");
		map.put(3, "C");
		Map<Integer, String> immutableMap2 = Map.copyOf(map);
		
		String[] arr = { "A", "B", "C" };
		List<String> immutableList3 = Arrays.asList(arr);
	}

}

'Language > JAVA' 카테고리의 다른 글

[JAVA] 람다식 참조  (0) 2024.10.21
[JAVA] 람다식  (0) 2024.10.21
[JAVA] 동기화된 컬렉션  (0) 2024.10.18
[JAVA] LIFO와 FIFO 컬렉션  (1) 2024.10.18
[JAVA] 검색 기능을 강화시킨 컬렉션  (0) 2024.10.18