본문 바로가기
Study/Java

[Java] java.util.Collections 주요 메소드 정리

by 검프 2021. 4. 10.

설명에 앞서, 컬렉션의 중복되는 의미들을 살펴볼게요

컬렉션의 중복되는 의미들

1.collection(소문자 c): 객체가 저장되고 반복되는 자료 구조를 나타냅니다.

2.Collection(대문자 C): Set, List, Queue가 상속받는 java.util.Collection 인터페이스입니다. ( 이는 상속입니다. 구현이 아니라. 즉, Collection를 직접 구현한 것은 없습니다. )

3.Collections(대문자 C, s로 끝남): collections에 사용할 정적 유틸리티 메소드의 모음이 있는 java.util.Collections 클래스입니다.

 

1, 2에 관련된 내용은 아래 포스팅에서 다뤘어요.

[Java] 컬렉션 프레임워크(Collections Framework)

이번 포스팅에서 살펴 볼 것은 3번, Collections예요.
제가 자주 썻던 메소드들만 자세히 정리해보려고 해요.

 

Collections 클래스

큰 특징으로는

컬렉션 프레임워크 타입의 객체에서 사용하거나 컬렉션을 반환하는 static 메소드들로 구성되어있어요.

반환된 컬렉션에서 add, setter와 같은 수정자를 허용하지 않고, UnsupportedOperationException을 던져요. 즉, 수정을 허용하지 않아요.

쉽게 말해 컬렉션 프레임워크 타입의 객체(중복되는 의미에서 1번)에 대한 객체생성, 정렬, 병합, 검색 등의 알고리즘이 구현되어있는 클래스예요.


 

Methods

unmodifiableList(List<? extends T> list)

public static List unmodifiableList(List<? extends T> list)

view에 특화된 추가, 삭제 할 수 없는 List를 반환해요. 이를 통해 모듈은 내부 목록에 대한 "읽기 전용"엑세스를 제공 할 수 있어요.
저는 주로 일급컬렉션에서 속성을 반환할 때 사용해요.

public class Cars {
    private final List<Car> cars;

    private Cars(final List<Car> cars) {
        List<Car> copy = new ArrayList<>(cars);    //인자로 넘어온 객체의 참조를 끊음
        validateCars(copy);
        this.cars = copy;
    }

    public List<Car> getCars() {
        return Collections.unmodifiableList(cars);    //반환해줄 리스트의 추가 삭제를 막음.
}

emptyList()

public static final List emptyList()

불변의 List를 반환해요. 반환된 List는 직렬화 가능해요.

초기화할 변수에서 타입추론해요.

List<Car> emptyCars = Collections.emptyList();
List<String> emptyNames = Collections.emptyList();

singletonList(T o)

public static List singletonList(T o)

인자로 넘긴 객체 하나만 포함하는 불변의 List를 반환해요.

Arrays.asList()와 차이점에 대해서 이는 이전 포스트에서 다뒀어요.

[Java] Arrays.asList() vs Collections.singletonList()

List<Integer> singletonNumbers = Collections.singletonList(5);
singletonNumbers.set(0, 8);        //UnsupportedOperationException 발생

shuffle(List<?> list)

public static void shuffle(List<?> list)

미리 지정된 임의의 조건에 따라 컬렉션 요소를 무작위로 변경해요.

List<Integer> numbers = Arㄹrays.asList(1, 2, 3, 4, 5);
Collections.shuffle(numbers);
System.out.println("numbers = " + numbers); // 램덤으로 섞인 값 출력 

sort(List list)

public static <T extends Comparable<? super T>> void sort(List list)

프리미티브 타입일 때

의미상 오름차순으로 정렬돼요.

List<Integer> numbers = Arrays.asList(5, 4, 3, 2, 1);
List<Double> doubleNumbers = Arrays.asList(5d, 4d, 3d, 2d, 1d);

Collections.sort(numbers);
Collections.sort(doubleNumbers);

System.out.println("numbers = " + numbers);    //numbers = [1, 2, 3, 4, 5]
System.out.println("doubleNumbers = " + doubleNumbers);    //doubleNumbers = [1.0, 2.0, 3.0, 4.0, 5.0]

래퍼런스 타입일 때

Comparable을 구현한 클래스의 조건에 따라 정렬돼요.

public class LottoBall implements Comparable<LottoBall> {
    private final int value;

    public LottoBall(final int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    @Override
    public int compareTo(LottoBall o) {
        if (this.value > o.value) {
            return 1;
        }
        return -1;
    }
}

public static void main(String[] args) {
    List<LottoBall> lottoBalls = Arrays.asList(new LottoBall(5),
               new LottoBall(4),
               new LottoBall(3),
               new LottoBall(2),
               new LottoBall(1));
    Collections.sort(lottoBalls);
    for (LottoBall lottoBall : lottoBalls) {
        System.out.print(lottoBall.getValue() + " ");    // 1 2 3 4 5
    }
}

reverse(List list)

public static void reverse(List<?> list)

위에 작성한 sort의 역순으로 정렬해요.

max(Collection<? extends T> coll)

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

프리미티브 타입일 때

비교한 요소 중 의미상 가장 큰 값을 찾아요.

List<Integer> numbers = Arrays.asList(5, 4, 3, 2, 1);
List<Integer> minusNumbers = Arrays.asList(-5, -4, -3, -2, -1);
List<String> alphabets = Arrays.asList("a", "b", "c", "d", "e");

System.out.println(Collections.max(numbers));    //5
System.out.println(Collections.max(minusNumbers));    //-1
System.out.println(Collections.max(alphabets));    //e

래퍼런스 타입일 때

Comparable을 구현한 클래스의 조건에 따라 비교한 요소 중 가장 큰 값을 찾아요.

public class LottoBall implements Comparable<LottoBall> {
    private final int value;

    public LottoBall(final int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    @Override
    public int compareTo(LottoBall o) {
        if (this.value > o.value) {
            return 1;
        }
        return -1;
    }
}

public static void main(String[] args) {
    List<LottoBall> lottoBalls = Arrays.asList(new LottoBall(1),
               new LottoBall(2),
               new LottoBall(3),
               new LottoBall(4),
               new LottoBall(5));
    System.out.println(Collections.max(lottoBalls).getValue());    //5
}

min(Collection<? extends T> coll)

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

위에 작성한 max의 반대로 최솟값을 찾아요.

Refer

https://codevang.tistory.com/139

댓글