想象我有两个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) –