返回SortedSet

时间:2015-01-27 19:21:05

标签: java collections 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 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);
  }

它将打印出我的学生对象的名称列表。现在我想按字母顺序排列。我认为它就像使用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);
 }

但这只会抛出异常:

  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)

Java结果:1

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

 public int compareTo(Student other)
 {
   return this.getName().compareTo(other.getName());
 }

2 个答案:

答案 0 :(得分:7)

“订单”是什么意思?如果您按照添加顺序表示,则只需使用LinkedHashSet。如果您想要某种排序,那么您必须通过Student实施Student或提供Comparable<Student>来描述Comparator<Student>的排序方式。

如果您按字母顺序排列,那么您应该修改Student类,如下所示:

class Student implements Comparable<Student> {
   ...
   public int compareTo(Student other) {
     return getName().compareTo(other.getName());
   }
}

答案 1 :(得分:1)

对于字母顺序,您有两种方式。

  1. 通过实施类似的界面来改变您的学生课程。

    原因: - 当我们向TreeSet添加元素时,对于Treeset中的每个现有对象,JVM通过调用它们上的compareTo / compare方法来比较当前对象,并通过实现Comparable接口,我们提供compareTo方法实现。

  2. OR-在创建TreeSet时提供Comparator对象,即

    Collection<Student> tm = new TreeSet<Student>(new Comparator<Student>() {
    
        @Override
        public int compare(Student o1, Student o2) {
            return o1.getName().compareTo(o2.getName());
        }
    
    });
    

    在这里,我使用了匿名的Comparator.Hope this Helps。