且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

返回SortedSet

更新时间:2022-10-15 16:37:42

订购?如果你的意思是按他们添加的顺序,那么只需使用 LinkedHashSet 。如果你想要某种排序,那么你必须描述 Student s应该如何通过 Student 实现可比较的< Student> 或提供比较器< Student>



如果你是按字母排序,那么你应该修改 Student 类,例如:

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


When I run the following code:

  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);
  }

It will print out a list of names for my student objects. Now I'd like to do them in alphabetical order. I thought it would be as simple as using a TreeSet or SortedSet.

Like this:

 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);
 }

But this just throws the exception:

  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 Result: 1

I have added a compareTo method in the student class too:

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

What do you mean by "order"? If you mean in the order they were added, then just use LinkedHashSet. If you want some kind of sorting, then you have to describe how Students should be sorted by having Student implement Comparable<Student> or by providing a Comparator<Student>.

If you meant alphabetical order, then you should modify the Student class like so:

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