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