简体   繁体   English

使用 Collections.sort() 对自定义对象进行排序

[英]Sorting Custom Objects with Collections.sort()

I am trying to sort custom objects using Collections.sort in java and I am running into this error, with the following code:我正在尝试使用 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;
   }
}

This is the error:这是错误:

StudentClient.java:14: error: incompatible types: void cannot be converted to ArrayList<Student>
      ArrayList<Student> sortedStudents = Collections.sort(students);

How do I fix this error?如何修复此错误? Why is collections.sort returning a void type?为什么 collections.sort 返回 void 类型?

This is a compile time error.这是一个编译时错误。 sort works on the same list you provide, it doesn't return a new one. sort适用于您提供的相同列表,它不会返回新列表。

So just change this:所以只要改变这个:

ArrayList<Student> sortedStudents = Collections.sort(students);
System.out.println(sortedStudents);

For this为了这

Collections.sort(students);
System.out.println(students);

Update : Reference documentation更新:参考文档

All java classes are well documented on what's named javadoc (java documentation).所有 java 类都在名为 javadoc(java 文档)的内容中有详细记录。 There you can find every specification of classes, methods, return types, etc, etc, with explanations and sometimes even examples.在那里你可以找到类、方法、返回类型等的每个规范,以及解释,有时甚至是示例。

In your case, a quick look here would have been really helpful:在您的情况下,快速浏览这里会非常有帮助:

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

Have a look at the documentation of Collections.sort(List) .查看Collections.sort(List)的文档。 It says Sorts the specified list into ascending order .它说Sorts the specified list into ascending order It won't return a new sorted list, but instead sort the existing list.它不会返回新的排序列表,而是对现有列表进行排序。

If you want a new sorted list you can use Stream or copy the list and then sort the copy.如果您想要一个新的排序列表,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM