Java 컬렉션

Copyright (c) 2015-, All Rights Reserved by Kwanghoon Choi
(아래 자바 프로그래밍 강의 교재의 내용을 자유롭게 이용하되 다른 웹 사이트 등을 통한 배포를 금합니다.)

1. Java 컬렉션(collection)

Java 컬렉션 프레임워크는 java.util (과 java.util.concurrent) 패키지에 포함된 인터페이스들과 클래스들의 집합이다. 여러 객체들을 모아 관리하는 모델을 인터페이스들을 통해 정의하고 인터페이스를 구현하는 클래스들을 통해 이 모델을 지원하는 여러가지 방법을 제공한다. Java 컬렉션 프레임워크를 구성하는 주요 인터페이스와 클래스는 다음과 같다.


                   Iterable<T>
                   (java lang)
			|
                  Collection<E>
                        |
     +------------------+-----------------+
     |			|      	       	  |
   Set<E>            List<E>           Queue<E>
     |                                    |
     |			       +----------+-----------+
     |			       |          	      |
 SortedSet<E>                  |                   Deque<E>
     |			       |                      |
NavigableSet<E>       BlockingQueue<E>                |
                      (java.util.concurrent)          |
                               |                      |
                               +-------------------+  |
                                                   |  |
                                             BlockingDeque<E>
                                          (java.util.concurrent)

             Map<K,V>
                 |
        +--------+---------+
        |		   |
 SortedMap<K,V>            |
        |            ConcurrentMap<K,V>
        |           (java.util.concurrent)
NavigableMap<K,V>          |
        |                  |
        +-------+ +--------+
                | |
      ConcurrentNavigableMap<K,V>
        (java.util.concurrent)

각 클래스와 인터페이스에 포함된 메소드는 Java API 문서를 참고한다. - http://docs.oracle.com/javase/

1.1  컬렉션 라이브러리

첫째, 반복해서 원소를 꺼낼때 유용한 Iterable 인터페이스의 정의는 다음과 같다.

package java.lang;
public interface Iterable<T> { 
   Iterator<T> iterator();
}

package java.util;
public interface Iterator<E> {
   boolean hasNext();  // Returns true if the iteration has more elements.
   E next();           // Returns the next element in the iteration.
   void remove();      // Removes from the underlying collection the last 
                       // element returned by this iterator.
}

일반적으로 배열이나 컬렉션 클래스과 함께 foreach 문을 사용하지만, Iterable 인터페이스를 직접 구현한 클래스와 함께 foreach 문을 사용할 수도 있다. 예를 들어, 카운터 클래스를 정의하고 Iterable 인터페이스를 구현해보자.

class Counter implements Iterable<Integer> 
{
   private int count;
   public Counter(int count) { this.count = count; }
   public Iterator<Integer> iterator() { return new MyIterator(); }

   class MyIterator implments Iterator<Integer> {
      private int i = 0;
      public boolean hasNext() { return i < count; }
      public Integer next() { i++; return i; }
      public void remove() { throw new UnsupportedOperationException(); }
   }
}

아래 코드에서 카운터 클래스와 foreach 문을 함께 사용한다.

int total = 0;
for (int i : new Counter(3)) {
   total += i;
}

// total == 6

 

둘째, 컬렉션 클래스 Collections에서 다형 알고리즘(Polymorphic algorithms)을 제공한다. 그 중 하나로 문자열 리스트를 정렬하는 예는 다음과 같다.

import java.util.*;

public class Sort {
    public static void main(String[] args) {
        List list = Arrays.asList(args);
        Collections.sort(list);
        System.out.println(list);
    }
}

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *