[자바]no suitable method found for sort(int[],(a,b)->Int[...]a, b)) Arrays.sort(numbers, (a, b) -> Integer.compare(a, b));
자바에서 custom comparator를 사용하려고 했는데 에러가 발생했습니다.
public String solution(int[] numbers) {
Arrays.sort(numbers, (a, b) -> Integer.compare(a, b));
람다식으로도 사용해보고 compare함수도 사용해보고 했는데 계속 에러가 떴습니다.
error: no suitable method found for sort(int[],(a,b)->Int[...]a, b)) Arrays.sort(numbers, (a, b) -> Integer.compare(a, b)); ^ 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>) |
이유를 찾아보니 primitive 타입에 대한 Comparator가 없기 때문입니다.
int[]이 아닌 Integer[]이 1번째 인자로 들어가야 합니다.
자바에서는 이처럼 primitive 타입인지 아니면 객체인지에 따라 사용의 제약이 있는 경우가 있습니다.
이번에는 잘 기억해놔야 겠네요 ㅎㅎ;;
그리고 int배열을 Integer배열이나 ArrayList<Integer>로 손쉽게 바꿀 수 있는 방법은 없습니다. Lambda 쓰거나 for문 돌려야 합니다.
Integer배열이면 Arrays.sort함수로 정렬을 해야하고, ArrayList<Integer>는 Collections.sort함수로 정렬해야 합니다.
참고
no suitable method found for sort, inference array variable has incompatible bounds
The function tries to transform the array into a pendulum form. Like the input is: 1 3 2 5 4 The answer should be: 5 3 1 2 4 The minimum is in between. public static void printPendulum(int...
stackoverflow.com
stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java
How to convert int[] into List in Java?
How do I convert int[] into List in Java? Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as ...
stackoverflow.com
댓글 영역