PHpullh
학습 라이브러리/Java/Collections 유틸리티

JAVA · 컬렉션

Collections 유틸리티

Collections 클래스의 유용한 정적 메서드를 활용합니다.

컬렉션중급Collections유틸리티정렬불변

핵심 설명

Collections 클래스의 유용한 정적 메서드를 활용합니다.

Java code

import java.util.*;

public class CollectionsUtil {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(List.of(3, 1, 4, 1, 5, 9));

        // 정렬
        Collections.sort(list);
        System.out.println(list); // [1, 1, 3, 4, 5, 9]

        // 이진 검색 (정렬 후)
        int idx = Collections.binarySearch(list, 4);
        System.out.println("4의 인덱스: " + idx);

        // 최대/최소
        System.out.println("최대: " + Collections.max(list));
        System.out.println("최소: " + Collections.min(list));

        // 셔플
        Collections.shuffle(list);
        System.out.println("셔플: " + list);

        // 빈도
        System.out.println("1의 빈도: " + Collections.frequency(list, 1));

        // 불변 래퍼 (읽기 전용 뷰)
        List<Integer> readOnly = Collections.unmodifiableList(list);
        // readOnly.add(10); // UnsupportedOperationException

        // 동기화 래퍼
        List<Integer> syncList = Collections.synchronizedList(
            new ArrayList<>());

        // 싱글톤 / 빈 컬렉션
        List<String> single = Collections.singletonList("only");
        List<String> empty = Collections.emptyList();
        // Java 9+에서는 List.of("only"), List.of() 권장
    }
}

학습 팁

Java 9+ 팩토리 메서드(List.of(), Map.of())가 Collections.unmodifiable*()보다 간결하고 메모리 효율적입니다.

주의할 점

Collections.unmodifiableList()는 원본을 래핑한 뷰입니다. 원본 리스트를 변경하면 뷰에도 반영됩니다.

자주 묻는 질문

Collections 유틸리티란 무엇인가요?

Collections 클래스의 유용한 정적 메서드를 활용합니다.

Collections 유틸리티 학습 시 주의할 점은 무엇인가요?

Collections.unmodifiableList() 는 원본을 래핑한 뷰입니다. 원본 리스트를 변경하면 뷰에도 반영됩니다.