想象我有兩個POJO豆狀:Java的泛型方法調用在Java
public class Employee {
private String name;
private long id;
....
//GETTERS AND SETTERS
}
public class Buildings {
private String name;
private long numOfEmployees;
...
//GETTERS AND SETTERS
}
現在我做這些的POJO的兩個列表(empList & bldList),我想使用Collections.sort功能,這樣對它們進行排序:
Collections.sort(empList , new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return o2.getId().compareTo(o1.getId());
}
});
和另一個排序是這樣的:
Collections.sort(bldList, new Comparator<Buildings>() {
public int compare(Buildings o1, Buildings o2) {
return o2.getNumOfEmployees().compareTo(o1.getNumOfEmployees());
}
});
現在
代替鄰˚F寫比較兩次爲了這個,我在想,我發現我可以使用泛型和方法做這裏面操作的解決方案,有什麼來到我的腦海裏是一個類似的方法:
public <T> List<T> sortMyList(List<T> list){
Collections.sort(list, new Comparator<T>() {
public int compare(T o1, T o2) {
// I don't know how to call the Building and Employee methods here so I just show it with "???"
return o1.???.compareTo(o2.???);
}
});
}
我怎樣才能讓這種方法適合我嗎?
問題的類都實現'Comparable'代替。 http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List)另請參閱:http://docs.oracle.com/javase/tutorial /collections/interfaces/order.html –
[如何在Java中對對象數組進行排序?](http://stackoverflow.com/questions/18895915/how-to-sort-an-array-of-objects -in-java) –