티스토리 뷰

개발자/자바(Java)

[Java] Arrays.sort 관련

BiteSnail 2024. 2. 27. 13:30

서론

Arrays.sort에서 기본형 배열을 사용할 때 주의점을 소개합니다.

본론

Comparator

Arrays.sort를 사용할 때 기본형 배열 int[], char[], long[] 등을 사용한다면 Comparator를 만들어 사용할 수 없습니다. 그래서 아래와 같은 에러가 발생합니다.

error: no suitable method found for sort(int[],(a,b)->b - atable method found for sort(int[],(a,b)->b - a`table method found for sort(int[],(a,b)->b - atable method found for sort(int[],(a,b)->b - a`)
        Arrays.sort(nums, (a, b) -> b - a);
              ^
    method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: int
        lower bounds: Object)
    method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
    T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)

따라서 Wrapper 클래스를 사용하거나 stream으로 만들어 사용해야 합니다.

stream을 사용한 정렬

boxed 메서드를 이용해 기본형을 클래스로 감싼 후 sorted 메서드를 이용해 정렬합니다. 이때 새로운 comparator를 정의해서 사용할 수 있습니다.

int[] array = {1, 2, 3};
array = Arrays.stream(array).boxed().sorted((idx1, idx2) -> idx1 - idx2).mapToInt(Integer::intValue).toArray();

wrapper를 사용하는 방법

굳이 권장하지는 않지만 반드시 Arrays.sort를 사용해야 한다면 아래와 같이 사용하는 것도 하나의 방법인 것 같습니다.

Integer[] arrs = Arrays.stream(array).boxed().toArray(Integer[]::new);
Arrays.sort(arrs, (idx1, idx2) -> idx1-idx2);`

결론

Wrapper 클래스를 사용하는 방법을 또 하나 깨달았습니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함