0
假设我有一个学生名单:ArrayList<Student> student = new ArrayList<>();
。学生类看起来是这样的:按两个属性排序对象
public class Student {
String name;
int age;
String hobby;
//getter and Setter methods below
}
我想排序名称列表,但如果名称是平等的,我想岁以后它排序。我怎样才能在Java中做到这一点。
,这个我已经名排序是:
public class MyComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
if(o1.getName() > o2.getName()){
return 1;
}
else if(o1.getName() < o2.getName())
{
return -1;
}
else{
return 0;
}
}
}
因此,如果他们有相同的名字,我怎么能岁以后排序呢? 最后我想要Collections.sort(student, MyComparator comp)
来排序列表。
[地产自定义对象的排序的ArrayList(可能的重复http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-by-property) –
'return o1.getAge() - o2.getAge();'而不是'return 0;'? – Breeze
而不是返回0你应该检查年龄。 – kukudas