今天我被问到这个面试问题:
如果我有一个
Person带班name,age和salary领域,我把这个100个新的实例Person中的ArrayList,然后做Collections.sort(list),然后什么参数将列表进行排序?
我知道我需要有Person类实现Comparable然后覆盖compareTo,但如果我不这样做,会发生什么?
是的,您可以在不使元素实现Comparable Interface的情况下对集合进行排序,这样做
List<YourType> theList = new ArrayList<>();
Collections.sort(theList, new Comparator<YourType>(){
public int compare(YourType obj1, YourType obj2) {
// this method should return < 0, 0 or > 0
// whether obj1 is less than, equal to
// or greather than obj2
return 0;
}
});
Run Code Online (Sandbox Code Playgroud)
/编辑,
如果你使用Collections.sort(List),那么只有当列表是通用的并且它的元素实现Comparable时它才会编译.如果是这样,那么每个元素的compareTo(Obj)的实现将决定在调用sort(List)方法后列表中的排序
| 归档时间: |
|
| 查看次数: |
3472 次 |
| 最近记录: |