BE/JAVA

[JAVA] 추가,삭제 할 수 없는 컬렉션 만들기

スモモ🍒 2024. 6. 26. 16:47

수정할 수 없는 컬렉션

: 수정할 수 없는 컬렉션이란, 요소를 추가&삭제할 수 없는 컬렉션을 의미하며 컬렉션 생성시 저장된 요소를 변경하고 싶지 않을 때 유용하다. 

 

수정할 수 없는 컬렉션 만드는 방법 3가지

 

1) list, set, map를 정적메소드인 of()로 생성할 수 있다.

// 1) 정적메소드 of()사용
		// list 불변
		List<String> noAdd = List.of("A", "B", "C");
		
		// noAdd.add("D");	// 수정할 수 없기 때문에 추가 할 수 없다.
		
		System.out.println(noAdd);
		
		// set 불변
		Set<String> noChange = Set.of("A", "B", "C");
		
		// map 불변 (참고로 map은 출력시 랜덤하게 나온다)
		Map<Integer, String> Nop = Map.of(
				1, "A",
				2, "B",
				3, "C"
				);
		
		// Nop.put(4, "D");	// 수정할 수 없기 때문에 추가 할 수 없다.
		System.out.println(Nop);

 

2) list, set, map를 정적메소드인 copyOf()로 생성할 수 있다.

// 2) 정적메소드 copyOf()사용
		// list (출력시 오름차순)
		List<String> list = new ArrayList<>();
		list.add("A");
		list.add("B");
		list.add("C");
		List<String> upanddownCopy1 = List.copyOf(list);
		
		System.out.println("=====" + upanddownCopy1);
		
		// set (출력시 내림차순)
		Set<String> set = new HashSet<>();
		set.add("A");
		set.add("B");
		set.add("C");
		Set<String> upanddownCopy2 = Set.copyOf(set);
		
		System.out.println("=====" + upanddownCopy2);
		
		// map (출력시 랜덤)
		Map<Integer, String> map = new HashMap<>();
		map.put(1, "A");
		map.put(2, "B");
		map.put(3, "C");
		Map<Integer, String> upanddownCopy3 = Map.copyOf(map);
		
		System.out.println("=====" + upanddownCopy3);

 

3) list, set, map를 asList()로부터 수정할 수 없는 list컬렉션을 만든다.

// 3) asList() 사용하여 배열로부터 list 불변 컬렉션 생성
		String[] arr = {"A", "B", "C"};
		List<String> noModList = Arrays.asList(arr);
		System.out.println(arr);