【发布时间】:2015-06-05 20:36:14
【问题描述】:
例如,如果我想用 ID 对人进行排序,并且我编写了一个内部类来实现比较器,例如
public class IDCompare implements Comparator<People>{
// this order of compare will sort in ascending order
@Override
public int compare(People o1, People o2) {
return o1.getID() - o2.getID();
}
// this order of compare will sort in descending order
@Override
public int compare(People o1, People o2) {
return o2.getID() - o1.getID();
}
}
Collection.sort()方法是如何知道排序的顺序并根据输入的顺序实现my的?
【问题讨论】:
-
你试过编译那个代码吗?
-
如你所说,顺序由比较函数决定
-
(另外,你真的不应该使用这种方法来实现比较。它会导致极端值的问题。)
-
另外,当不提供比较器时,您只能对可比较对象进行排序,它们自己定义它们的顺序
标签: java sorting collections