返回SortedSet

Kha*_*hal 0 java collections sortedset treeset

当我运行以下代码时:

  Student student1 = new Student("Billy", 13);
  Student student2 = new Student("Bob", 12);
  Student student3 = new Student("Belle", 11);
  Student student4 = new Student("Barry", 10);
  Student student5 = new Student("Brian", 10);
  Student student6 = new Student("Bane", 13);
  Collection<Student> students = new HashSet<Student>();
  students.add(student1);
  students.add(student2);
  students.add(student3);
  students.add(student4);
  students.add(student5);
  students.add(student6);
  for(Student student : students)
  {
    String name = student.getName();
    System.out.println(name);
  }
Run Code Online (Sandbox Code Playgroud)

它将打印出我的学生对象的名称列表.现在我想按字母顺序排列.我认为它就像使用TreeSet或SortedSet一样简单.

像这样:

 Student student1 = new Student("Billy", 13);
 Student student2 = new Student("Bob", 12);
 Student student3 = new Student("Belle", 11);
 Student student4 = new Student("Barry", 10);
 Student student5 = new Student("Brian", 10);
 Student student6 = new Student("Bane", 13);
 Collection<Student> students = **new TreeSet<Student>();**
 students.add(student1);
 students.add(student2);
 students.add(student3);
 students.add(student4);
 students.add(student5);
 students.add(student6);
 for(Student student : students)
 {
    String name = student.getName();
    System.out.println(name);
 }
Run Code Online (Sandbox Code Playgroud)

但这只是抛出异常:

  Exception in thread "main" java.lang.ClassCastException: helloworld.Student cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:542)
    at java.util.TreeSet.add(TreeSet.java:238)
    at helloworld.Main.main(Main.java:60)
Run Code Online (Sandbox Code Playgroud)

Java结果:1

我也在学生班中添加了compareTo方法:

 public int compareTo(Student other)
 {
   return this.getName().compareTo(other.getName());
 }
Run Code Online (Sandbox Code Playgroud)

Lou*_*man 7

"订单"是什么意思?如果你的意思是他们被添加的顺序,那么就使用吧LinkedHashSet.如果你想要某种排序,那么你必须Student通过Student实现Comparable<Student>或提供一个来描述如何对s进行排序Comparator<Student>.

如果你的意思是字母顺序,那么你应该Student像这样修改类:

class Student implements Comparable<Student> {
   ...
   public int compareTo(Student other) {
     return getName().compareTo(other.getName());
   }
}
Run Code Online (Sandbox Code Playgroud)