【发布时间】:2019-04-18 09:54:53
【问题描述】:
在一个使用实现Comparator接口的类的项目中,为了比较一些可比较的对象,我注意到我可以设计实现Comparator<>接口的类带有字段,然后是Override compare(...) 函数,并将类的字段用于比较函数逻辑。
所以我必须像这样调用排序函数:
Collections.sort(someArrayList, new SortClass(argument1, argument2));
我的问题是:
这样的事情有多普遍?
这算不算好的设计?
假设我得到一个应该改变某些对象之间比较逻辑的用户输入,那么构建一个新的包装类(使用给定的参数)会被认为是一个更好的解决方案吗?
根据要求,我的 SortClass 是(我在上面的部分中对其进行了概括,但这是我真正的排序类):
public class SortHouses implements Comparator<Hotel> {
/** if house1 should be before house2 */
private static final int GT = -1;
/** if house1 should be after house2 */
private static final int LT = 1;
private double latitude;
private double longitude;
public SortHouses(double latitude, double longitude){
this.latitude = latitude;
this.longitude = longitude;
}
@Override
public int compare(House house1, House house2) {
double distHouse1 = Math.sqrt((Math.pow((house1.getLatitude() - latitude), 2) +
Math.pow((house1.getLongitude() - longitude), 2)));
double distHouse2 = Math.sqrt((Math.pow((house2.getLatitude() - latitude), 2) +
Math.pow((house2.getLongitude() - longitude), 2)));
if (distHouse1 < distHouse2){
return GT;
}
if (distHose1 > distHouse2) {
return LT;
}
if (house1.getNum() > house2.getNum()){
return GT;
}
return LT;
}
}
【问题讨论】:
-
你能显示你的
SortClass吗?这样做没有具体问题,但您可以改用Comparator.comparing(/* based on arg1 */).thenComparing(/* based on arg2 */)构建比较器。 -
为什么不在课堂上实现
comparable? -
你也可以不使用你自己的类来做到这一点。使用
Comparator.comparing(Function<? super T,? extends U>).thenComparing(Function<? super T,? extends U>)。 -
@HusamBdr 因为该类可能不包含其元素的自然顺序。考虑一个类
Car,它是一个EngineSorter。 -
@HusamBdr Comparable 仅用于自然排序。它不仅仅是一个“更简单”的比较器。如果我有一个类
Person并且我想按名称对它们进行排序,那么实现 Comparable 是没有意义的。人们不会自然地按姓名或任何其他标准排序。
标签: java comparator comparable