본문 바로가기
Java의 정석/컬렉션 프레임워크

Collections 컬렉션 클래스

by Hwanii_ 2023. 10. 10.
728x90

Collections - 컬렉션을 위한 메서드 (static == 정적 메서드 == 클래스 메서드) 를 제공 한다.

 

대표적인 static 메서드를 지니고 있는 클래스는 Objects / Arrays / Collections 이다.

Objects 클래스는 객체를 다룰 때 사용 하는 클래스 이다.

Arrays 클래스는 배열을 다룰 때 사용 하는 클래스 이다.

Collections 클래스는 컬렉션을 다룰 때 사용 하는 클래스 이다.

 

1.

컬렉션 채우기, 복사, 정렬, 검색

>> fill(), copy(), sort(), binarySearch(), .. 등등

 

2.

컬렉션의 동기화

>> synchronizedXXX()

 

static Collections synchronizedCollection(Collection c)

static List synchronizedList(List list)

static Set synchronizedSet(Set s)

static Map synchronizedMap(Map m)

static SortedSet synchronizedSortedSet(SortedSet s)

 

예전에는 컬렉션을 사용 하면 무조건 동기화를 지원 했었지만,

동기화 기능이 불필요한 경우, 낭비가 되므로,

지금은 컬렉션에 동기화 기능이 내장 되어 있지 않다. 

따라서, 동기화가 필요한 경우 위와 같이 각각의 컬렉션에 맞는 synchronizedXXX 메서드를 사용 하면 된다.

 

예시)

 

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

//	syncList 는 자바 유틸 클래스의 Collections 클래스의
//	static 메서드인 synchronizedList를 사용 해서
//	동기화가 된 배열리스트를 가리키는 참조변수 이다.

//	new ArrayList(...) 는 동기화 되지 않은 상태의 배열리스트 이다.

//	참고로 동기화된 배열리스트인 syncList는 vector 클래스를 사용하는것과 동일하다고 보면 된다.

//	vector 클래스는 동기화 내장 지원 하는 구버전의 클래스.

 

3.

변경 불가 (readOnly) 컬렉션 만드는 방법 ?

>> unmodifiableXXX()

 

 

4.

싱글톤 컬렉션 만드는 방법 ?

>> singletonXXX()

 

 

컬렉션에 오로지 객체 "한 개" 만 저장 할 수 있게 하는 개념이 싱글톤 이다.

 

5.

한 "종류" 의 객체만 저장 하는 컬렉션 만드는 방법 ?

>> checkedXXX()

 

 

예시)

 

List list = new ArrayList();
List checkedList = checkedList(list, String.class);	//	String.class 를 작성해서 String만 저장 가능하도록 함
checkedList.add("abc");	//	OK.
checkedList.add(new Integer(3));	//	에러 발생. ClassCastException 발생

 

하지만, 위의 checkedXXX() 메서드를 거의 사용 하지 않는다고 보면 된다.

 

왜냐하면 컬렉션에 제네릭을 사용해서 컬렉션에 저장할 타입을 명시해주면 되기 때문 이다.

 

이 제네릭 개념은 JDK 1.5 버전 부터 처음 나온 개념이다.

 

 

 

예제 01 )

 

package ch11;

import java.util.*;

import static java.util.Collections.*;

class Ex11_19 {

    public static void main(String[] args) {

        List list = new ArrayList();
        System.out.println("list : " + list);

        addAll(list, 1, 2, 3, 4, 5);
        System.out.println("addAll : " + list);

        rotate(list, 2);  // 반시계 방향으로 두번 회전
        System.out.println("rotate : " + list);

        swap(list, 0, 2); // 첫 번째와 세 번째를 교환(swap)
        System.out.println("swap : " + list);

        shuffle(list);    // 저장된 요소의 위치를 임의로 변경
        System.out.println("shuffle : " + list);

        sort(list, reverseOrder()); // 역순 정렬 reverse(list);와 동일
        System.out.println("sort -> reverseOrder() : " + list);

        sort(list);       // 정렬
        System.out.println("sort : " + list);

        int idx = binarySearch(list, 3);  // 3이 저장된 위치(index)를 반환
        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);

    }

}

 

[ console ]

 

반응형

'Java의 정석 > 컬렉션 프레임워크' 카테고리의 다른 글

TreeSet (2)  (1) 2023.10.09
TreeSet (1)  (0) 2023.10.09
HashSet (2)  (0) 2023.10.09
HashSet (1)  (0) 2023.09.20
Comparator & Comparable  (0) 2023.09.20