티스토리 뷰
서론
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 클래스를 사용하는 방법을 또 하나 깨달았습니다.
'개발자 > 자바(Java)' 카테고리의 다른 글
[Java] String의 stream과 char array 변환 (0) | 2024.02.26 |
---|---|
[Java] stream reduce 사용법 (0) | 2024.02.26 |
[Spring] Swagger 추가하기 (0) | 2024.02.23 |
[Spring] data source 설정하기 (0) | 2024.02.18 |
[Spring] 테스트 시 Lombok.extern.log4j does not exist 해결방법 (0) | 2024.02.18 |