본문 바로가기

프로그래밍/Java

Java_컬렉션프레임웍(7)_Collections의 메서드(동기화, 변경불가, 싱글톤, 단일 컬렉션), 컬렉션 클래스 정리

반응형

⑩ Collections의 메서드

  • Collections의 메서드 - 동기화(synchronized)

: Vector와 Hashtable과 같은 구버전 클래스들은 자체적으로 동기화 처리가 되어 있는데, 멀티쓰레드 프로그래밍이 아닌 경우에는 불필요한 기능이 되어 성능을 떨어뜨리는 요인이 된다. 

 

그래서 새로 추가된 ArrayList와 HashMap과 같은 컬렉션은 동기화를 자체적으로 처리하지 않고 필요한 경우에만 java.util.Collections클래스의 동기화를 이용해서 동기화처리가 가능하다.

 

동기화가 필요할 때 해당하는 것을 사용하면 된다. 

static Collection synchronizedCollection(Collection c)
static List synchronizedList(List list)
static Set synchronizedSet(Set s)
static Map synchronizedMap(Map m)
static SortedSet synchronizedSortedSet(SortedSet s)
static SortedMap synchronizedSortedMap(SortedMap m)

List syncList=Collections.synchronizedList(new ArrayList(...));

 

 

  • Collections의 메서드 - 변경불가(unmodifiable), 싱글톤(singleton)

- 변경불가 컬렉션 만들기

: 컬렉션에 저장된 데이터를 보호하기 위해 컬렉션을 변경할 수 없게 읽기 전용으로 만들어야 할 때 사용한다. 

static Collection unmodifiableCollection(Collection c)
static List unmodifiableList(List list)
static Set unmodifiableSet(Set s)
static Map unmodifiableMap(Map m)
static NavigableSet unmodifiableNavigableSet(NavigableSet s)
static SortedSet unmodifiableSortedSet(SortedSet s)
static NavigableMap unmodifiableNavigableMap(NavigableMap m)
static SortedMap unmodifiableSortedMap(SortedMap m)

 

- 싱글톤 컬렉션 만들기

: 단 하나의 객체만을 저장하는 컬렉션을 만들어야 할 때 사용한다. 

static List singletonList(Object o)
static Set singleton(Object o)
static Map singletonMap(Object key, Object value)

→ 매개변수로 저장할 요소를 지정하면, 해당 요소를 저장하는 컬렉션을 반환한다. 그리고 반환된 컬렉션은 변경할 수 없다.

 

 

 

  • Collections의 메서드 -  단일 컬렉션(chekced)

: 컬렉션에 모든 종류의 객체를 저장할 수 있다는 것은 장점이기도하고 단점이기도 하다. 대부분의 경우 한 종류의 객체를 저장하며, 컬렉션에 지정된 종류의 객체만 저장할 수 있도록 제한하고 싶을 때 사용한다. 

static Collection checkedCollection(Collection c, Class type)
static List checkedList(List list, Class type)
static Set checkedSet(Set s, Class type)
static Map checkedMap(Map m, Class keyType, Class valueType)
static Queue checkedQueue(Queue queue, Class type)
static NavigableSet checkedNavigableSet(NavigableSet s, Class type)
static SortedSet checkedSortedSet(SortedSet s, Class type

 

사용방법은 다음과 같이 두 번째 매개변수에 저장할 객체의 클래스를 지정하면 된다. 

List list=new ArrayList();
List checkedList=checkedList(list, String.class);
checkedList.add("abc");
checkedList.add(new Integer(3));	//에러.

 

 

- Collections 예제

import java.util.*;
import static java.util.Collections.*;

class JavaJungsuk_Framework_Collections {
    public static void main(String[] args) {
        List list=new ArrayList();
        System.out.println(list);
        
        addAll(list, 1, 2, 3, 4, 5);
        System.out.println(list);
        
        rotate(list, 2);	//반시계방향으로 두 번 회전.
        System.out.println(list);
        
        swap(list, 0, 2);	//첫번째와 세번째를 교환.
        System.out.println(list);
        
        shuffle(list);	//저장된 요소의 위치를 임의로 변경.
        System.out.println(list);
        
        sort(list, reverseOrder());	//역순 정렬 reverse()와 동일.
        System.out.println(list);
        
        sort(list);	//정렬.
        System.out.println(list);
        
        int idx=binarySearch(list, 3);	//3이 저장된 위치를 반환.
        System.out.println("index of 3="+idx);
        
        System.out.println("max="+max(list));
        System.out.println("min="+min(list));
        System.out.println("min="+max(list, reverseOrder()));
        
        fill(list, 9);	//list를 9로 채움.
        System.out.println("list="+list);
        
        //list와 같은 크기의 새로운 list를 생성하고 2로 채운다. 단 결과는 변경불가
        List newList=nCopies(list.size(), 2);
        System.out.println("newList="+newList);
        
        System.out.println(disjoint(list, newList));	//공통요소가 없으면 true
        
        copy(list, newList);
        System.out.println("newList="+newList);
        System.out.println("list="+list);
        
        replaceAll(list, 2, 1);
        System.out.println("list="+list);
        
        Enumeration e=enumeration(list);
        ArrayList list2=list(e);
        
        System.out.println("list2="+list2);
    }
}
결과
[]
[1, 2, 3, 4, 5]
[4, 5, 1, 2, 3]
[1, 5, 4, 2, 3]
[4, 1, 2, 3, 5]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
index of 3=2
max=5
min=1
min=1
list=[9, 9, 9, 9, 9]
newList=[2, 2, 2, 2, 2]
true
newList=[2, 2, 2, 2, 2]
list=[2, 2, 2, 2, 2]
list=[1, 1, 1, 1, 1]
list2=[1, 1, 1, 1, 1]

 

 

 

<컬렉션 클래스 정리 & 요약>

컬렉션 특징
ArrayList 배열기반, 데이터의 추가와 삭제에 불리, 순차적인 추가삭제는 제일 빠름. 임의의 요소에 대한 접근성이 뛰어남.
LinkedList 연결기반. 데이터의 추가와 삭제에 유리. 임의의 요소에 대한 접근성이 좋지 않다.
HashMap 배열과 연결이 결합된 형태. 추가, 삭제, 검색, 접근성이 모두 뛰어남. 검색에는 최고 성능을 보인다.
TreeMap 연결기반. 정렬과 검색(특히 범위검색)에 적합. 검색성능은 HashMap보다 떨어짐.
Stack Vector를 상속받아 구현
Queue LinkedList가 Queue인터페이스를 구현
Properties Hashtable을 상속받아 구현
HashSet HashMap을 이용해서 구현
TreeSet TreeMap을 이용해서 구현
LinkedHashMap
LinkedHashSet
HashMap과 HashSet에 저장순서 유저기능을 추가
반응형