[Java] Class Collections

by 민갤

Java /

Collection Framework

데이터 군을 저장하는 클래스들을 표준화한 설계

컬렉션 Collection :  다수의 데이터. 데이터 그룹

프레임웍 Framework :  표준화된 프로그래밍 방식.

Class Collections

컬렉션과 관련된 메서드를 제공한다.

fill(), copy(), sort(), binarySearch()등의 Arrays와 동일한 메서드가 있으며, 같은 기능을 한다.

컬렉션의 동기화 Synchronization

멀티 쓰레드(Multi-Thread) 프로그래밍에서는 하나의 객체를 여러 쓰레드가 동시에 접근할 수 있기 때문에

데이터의 일관성을 유지하기 위해서 공유되는 객체를 동기화한다.

  • Vector, Hashtable 등의 구 버전(JDK1.2 이전) 클래스

     자체적으로 동기화 처리.

     멀티 쓰레드 프로그래밍이 아닌 경우에는 불필요한 기능이 되어 성능을 떨어트린다.

  • ArrayList, HashMap과 같은 컬렉션

     필요한 경우에만 java.util.Collections 클래스의 동기화 메서드를 이용하여 동기화 처리.

동기화 메서드

static Collection synchronizedCollection(Collection c)
static List synchronizedList(List list)
static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
static Set synchronizedSet(Set s)
static <K, V> SortedMap<K, V> synchronizedSortedMap(SortedMap<K, V> m)
static SortedSet synchronizedSortedSet(SortedSet s)
  • 사용하는 방법
Collection<String> c = Collections.synchronizedCollection(new Vector<String>());
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
List<Integer> syncList = Collections.synchronizedList(list);

변경불가 컬렉션 만들기

멀티 쓰레드 프로그래밍할 때 여러 쓰레드가 하나의 컬렉션을 공유하면서 데이터가 손상되는 것을 방지한다.

컬렉션에 저장된 데이터를 보호하기 위해 컬렉션을 읽기 전용으로 만든다.

static Collection unmodifiableCollection(Collection<? extends T> c)
static List unmodifiableList(List<? extends T> list)
static <K, V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m)
static Set unmodifiableSet(Set<? extends T> s)
static <K, V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m)
static SortedSet unmodifiableSortedSet(SortedSet s)

싱글톤 컬렉션 만들기

'singleton'으로 시작하는 메서드.

인스턴스를 new 연산자가 아닌 메서드를 통해서만 생성하게 해서

생성할 수 있는 인스턴스의 개수를 제한하는 방법과 같은 기능을 제공한다.

반환된 컬렉션은 변경할 수 없다.

static Set singleton(T o)
static List singletonList(T o)
static <K, V> Map<K, V> singletonMap(K key, V value)

한 종류의 객체만 저장하는 컬렉션 만들기

컬렉션에 지정된 종류의 객체만 저장할 수 있도록 제한할 때 사용한다.

JDK1.5 이전(지네릭스 도입 전)에 작성된 코드를 사용할 때 사용된다.

static Collection checkedCollection(Collection c, Class type)
static List checkedList(List list, Class type)
static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class keyType, Class valueType)
static Set checkedSet(Set s, Class type)
static <K, V> SortedMap<K, V> checkedSortedMap(SortedMap<K, V> m, Class keyType, Class valueType)
static SortedSet checkedSortedSet(SortedSet s, Class type)
  • 사용하는 방법
ArrayList<Integer> list = new ArrayList<>();
List<Integer> checkList = Collections.checkedList(list, Integer.class);
checkList.add("abs");        // error
checkList.add(1);

그 외 메서드 예제

package blog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();

        print(list + ""); // []

        Collections.addAll(list, 1, 2, 3, 4, 5);
        print(list + ""); // [1, 2, 3, 4, 5]

        print(Collections.binarySearch(list, 2) + ""); // 1

        Collections.rotate(list, 3);
        print(list + ""); // [3, 4, 5, 1, 2]

        Collections.swap(list, 0, 2);
        print(list + ""); // [5, 4, 3, 1, 2]

        Collections.shuffle(list);
        print(list + ""); // [1, 2, 5, 4, 3]

        Collections.sort(list);
        print(list + ""); // [1, 2, 3, 4, 5]

        Collections.sort(list, Collections.reverseOrder()); // == Collections.reverse(list);
        print(list + ""); // [5, 4, 3, 2, 1]

        Collections.reverse(list);
        print(list + ""); // [1, 2, 3, 4, 5]

        Collections.replaceAll(list, 3, 1);
        print(list + ""); // [1, 2, 1, 4, 5]

        Enumeration<Integer> e = Collections.enumeration(list);
        print(new ArrayList(Collections.list(e)) + ""); // [1, 2, 1, 4, 5]

        List<Integer> newList = Collections.nCopies(list.size(), 2);
        print(newList + ""); // [2, 2, 2, 2, 2]

        print(Collections.disjoint(list, newList) + ""); // false. 공통 요소가 없으면 true

        Collections.copy(list, newList);
        print(list + ""); // [2, 2, 2, 2, 2]

        Collections.fill(list, 8);
        print(list + ""); // [8, 8, 8, 8, 8]
    }

    public static void print(String str) {
        System.out.println(str);
    }
}

Collections API

참고 서적: 자바의 정석 3판 2

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

다음글 [Java] Generics

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓