我有以下代码,不知道为什么 list.sort 出现错误
public class Ccc{
public static void main(String[] args)throws IOException,ParseException{
File inFile = new File("C:\\Users\\shyic\\Desktop\\senior_data\\s3\\s3.27.in");
Scanner in = new Scanner (inFile);
int length = Integer.parseInt(in.nextLine());
ArrayList<Integer> list = new ArrayList<>();
while(in.hasNext()){
list.add (in.nextInt());
}
list.sort();
for (int i =0;i<10000;i+=1000){
System.out.println(list.get(i));
}
}
}
错误:
Error:(21, 13) java: no suitable method found for sort(no arguments)
method java.util.List.sort(java.util.Comparator<? super java.lang.Integer>) is not applicable
(actual and formal argument lists differ in length)
method java.util.ArrayList.sort(java.util.Comparator<? super java.lang.Integer>) is not applicable
(actual and formal argument lists differ in length)
最佳答案
如果你看the documentation ,您会看到该函数需要一个Comparator
。比较器实际上只是一个函数,它告诉排序函数如何进行排序 - 从低到高排序、从高到低排序、首先对所有偶数进行排序等。
Comparator
为了方便起见,类提供了一些常用的比较器,但是如果您需要一些不寻常的排序,您没有理由不能编写自己的比较器。
假设您想要整数的“自然排序”(从低到高),您可以使用:
list.sort(Comparator.naturalOrder());
如果你想从高到低排序,可以使用:
list.sort(Comparator.reverseOrder());
关于java - Arraylist.sort 请求比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45480840/