【发布时间】:2012-10-14 22:11:56
【问题描述】:
我有一个学生对象,然后我创建 ArrayList 并将学生添加到列表中。
ArrayList<Student_Object> studentsList = new ArrayList<>();
现在,我想按 studentId fleid 对列表进行排序。我该怎么做?
有没有更好的解决方案?谢谢
所以我在 Student _Object 类中有这个方法
班级是:
class Student_Object implements Comparator<Student_Object>
方法是:
public int compare(Student_Object student1, Student_Object student2){
String student1TUID = student1.getTUID();
String student2TUID = student2.getTUID();
return student1TUID.compareTo(student2TUID);
}
从哪里运行语句?
Collections.sort(studentsList);
如果我从我的主类运行它,我会在 netbeans 中得到错误:
no suitable method found for sort(ArrayList<Student_Object>)
method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
method Collections.<T#2>sort(List<T#2>) is not applicable
(inferred type does not conform to declared bound(s)
inferred: Student_Object
bound(s): Comparable<? super Student_Object>)
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
----
(Alt-Enter shows hints)
让它工作。我用 Collections.sort(studentsList, new Student_Object());
谢谢大家
【问题讨论】:
-
Student_Object 是多余的,使用 Student 就可以了
-
@RohitJain 实际上应该将它与“基于任意字段的排序列表”形式的新问题结合起来,但是这些组合似乎被击倒了。
标签: java arrays object arraylist