[英]Sorting Custom Objects with Collections.sort()
我正在尝试使用 java 中的 Collections.sort 对自定义对象进行排序,我遇到了这个错误,代码如下:
import java.util.ArrayList;
import java.util.Collections;
public class StudentClient {
public static void main(String[] args){
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("Jasper Holton", 12));
students.add(new Student("John Doe", 10));
ArrayList<Student> sortedStudents = Collections.sort(students);
System.out.println(sortedStudents);
}
}
public class Student implements Comparable<Student> {
public String name;
public int id;
public Student(String name){
this.name = name;
}
public Student(String name, int id){
this.name = name;
this.id = id;
}
...
@Override
public int compareTo(Student s){
return s.id - this.id;
}
}
这是错误:
StudentClient.java:14: error: incompatible types: void cannot be converted to ArrayList<Student>
ArrayList<Student> sortedStudents = Collections.sort(students);
如何修复此错误? 为什么 collections.sort 返回 void 类型?
这是一个编译时错误。 sort
适用于您提供的相同列表,它不会返回新列表。
所以只要改变这个:
ArrayList<Student> sortedStudents = Collections.sort(students);
System.out.println(sortedStudents);
为了这
Collections.sort(students);
System.out.println(students);
更新:参考文档
所有 java 类都在名为 javadoc(java 文档)的内容中有详细记录。 在那里你可以找到类、方法、返回类型等的每个规范,以及解释,有时甚至是示例。
在您的情况下,快速浏览这里会非常有帮助:
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
查看Collections.sort(List)
的文档。 它说Sorts the specified list into ascending order
。 它不会返回新的排序列表,而是对现有列表进行排序。
如果您想要一个新的排序列表,您可以使用Stream
或复制列表然后对副本进行排序。
//Stream
List<Student> sortedStudents = students.stream().sorted().collect(Collectors.toList());
//Copy
List <Student> sortedStudents = new ArrayList<>(students);
Collections.sort(sortedStudents);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.