Collection Framework Interface

yoon·2022년 9월 13일
0

1. Collection

Collection 은 Objects 의 그룹을 나타내는 root interface이다. Collection은 중복 요소를 허용하거나 그렇지 않을 수도, 정렬되어 있을 수도 그렇지 않을 수도 있다.

JDK 는 collection interface를 직접 implement 하는 것을 허용하지 않는다. 대신, Set, List 와 같은 subinterface 를 제공한다.

모든 Collection implementation class들은 2개의 "standard" constructors를 제공한다.

  • Void (no arguments) constructor
    : empty collection 을 생성한다.
  • Constructor with a single argument of type Collection
    : argument 와 같은 elemenet 를 갖는 collection 을 생성한다.

Collection 의 몇몇 methods 들은 optional 이다. 만약 collection implementation 이 method 를 구현하지 않았다면, UnsupportedOperationException 을 throw 하기 위한 method 를 구현해야 한다.

Collection implmentation 은 요소에 대한 제약을 두기도 한다. 부적격한 요소를 collection 에 추가하려고 할 경우, NullPointerException 이나 ClassCastException 과 같은 unchecked exception 을 throw 한다.

Collection implementation 은 own synchronizatino policy 를 갖는다.

2. List

public interface List<E> extends Collection<E>

2-1. 특징

  • 순서 O
  • 중복 O

2-2. 구현 클래스

  • Vector
    • public class Vector<E> implements List<E>
    • Stack: extends Vector
  • ArrayList
    • public class ArrayList<E> implements List<E>
    • 순차적인 접근에 강점
  • LinkedList
    • public class LinkedList<E> implements List<E>
    • 양방향 포인터 구조. 삽입/삭제가 빈번할 때 빠른 성능 보장.

3. Set

public interface Set<E> extends Collection<E>

3-1. 특징

  • 순서 X
  • 중복 X

3-2. 구현 클래스

  • HashSet
  • TreeSet

4. Map

public interface Map<K, V>

4-1. 특징

  • 순서 X
  • Key 는 중복 X Value 는 중복 O

4-2. 구현 클래스

  • HashMap
    • Array 의 index 를 hash 함수를 통해 계산 => get method O(1)
    • thread safe X
    • key 에 null 허용
  • TreeMap
    • Tree 구조 => get method O(logn)
    • SortedMap interface 구현하고 있어서 Key 값 기준으로 정렬되어 있음

5. 멀티 스레드 환경에서의 Collection

ArrayList, HashMap 은 멀티 스레드 환경에서 안전하지 않다.

자바에서는 Collections의 synchronizedXXX 메소드를 제공한다. 하지만, 동기화된 collection 은 스레드가 작업할 때 락이 발생하기 때문에 전체 요소를 빠르게 처리하지 못한다.

java.util.concurrent package 에서는 멀티스레드 환경에서 안전하면서도, 스레드가 병렬적으로 작업 처리할 수 있도록 ConcurrentHashMap, ConcurrentLinkedQueue 를 제공한다. 이 구현체는 부분 잠금(1개 요소 처리할 때 나머지 부분은 다른 스레드가 변경 가능)을 사용하기 때문에 병렬 작업이 가능하다.

0개의 댓글