Error:(33, 15) java: no suitable method found for sort(int[],java.util.Comparator<java.lang.Object>)
method java.util.Arrays.<T>sort(T[],java.util.Comparator<? super T>) is not applicable
(inference variable T has incompatible bounds
equality constraints: int
lower bounds: java.lang.Object)
method java.util.Arrays.<T>sort(T[],int,int,java.util.Comparator<? super T>) is not applicable
(cannot infer type-variable(s) T
(actual and formal argument lists differ in length))我不明白为什么Array.sort(num, Collections.reverseOrder())中的num是错误的?
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();
int[] num = new int[3];
num[0] = a;
num[1] = b;
num[2] = c;
Arrays.sort(num, Collections.reverseOrder());
for (int i = 0; i < num.length; i++) {
System.out.println(num[i] + " ");
}还有别的办法可以解决吗?
发布于 2020-07-30 20:55:07
没有Arrays.sort方法接受int[]和Comparator --接受Comparator的方法请求Object数组或Object的任何子类(例如Integer[])。
背景信息:类型变量(泛型)不能引用原语,因此
<T> void sort(T[], Comparator<? super T>)对int[]无效。
发布于 2020-07-30 21:02:45
我可以推荐您使用Java 8流。我会这样做:
Stream.of(num).sorted(Collections.reverseOrder());如果您想使用Arrays.sort(),那么只需要选择int[]作为第一个参数来提供另外两个参数(int fromIndex,int toIndex),这也是使用(int[],比较器)参数获得异常的原因。
发布于 2020-07-30 20:59:01
使用ArrayList代替
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a);
list.add(b);
list.add(c);
Comparator c1 = Collections.reverseOrder();
Collections.sort(list,c1);
System.out.println("Desending Order : " + list);
}
}这就行了。您可以使用数组进行初始化。
下面的代码为我使用了Array
import java.util.Arrays;
import java.util.Collections;
public class Main
{
public static void main(String[] args)
{
Integer[] arr = {2, 1, 3};
Arrays.sort(arr, Collections.reverseOrder());
System.out.printf("Desending Order : %s", Arrays.toString(arr));
}
} https://stackoverflow.com/questions/63181184
复制相似问题