当我运行以下代码时:
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());
}发布于 2015-01-28 03:23:08
你说的“订单”是什么意思?如果您是指按添加顺序,那么只需使用LinkedHashSet即可。如果您想要某种排序,那么必须通过让Student实现Comparable<Student>或提供Comparator<Student>来描述应该如何对Student进行排序。
如果您的意思是按字母顺序排序,那么您应该像这样修改Student类:
class Student implements Comparable<Student> {
...
public int compareTo(Student other) {
return getName().compareTo(other.getName());
}
}发布于 2015-01-28 04:03:44
对于字母顺序,您有两种方法。
Reason:当我们将元素添加到TreeSet中时,对于Treeset中的每个现有对象,JVM通过调用它们的compareTo/compare方法来比较当前对象,并通过实现可比较接口来提供compareTo方法TreeSet提供一个比较器对象,即
集合tm =新的比较器(TreeSet比较器(){ @Override public int compare(学生o1,学生o2) { return o1.getName().compareTo(o2.getName());} });
在这里,我使用了匿名Comparator.Hope,这很有帮助。
https://stackoverflow.com/questions/28178337
复制相似问题