微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-具有字段的比较器类

一个使用实现了Comparator接口的类的项目中,为了在一些可比较的对象之间进行比较,我注意到我可以设计实现Comparator接口的类.与字段进行接口,然后重写compare(…)函数,并将类的字段用于比较函数逻辑.

所以我必须像这样调用sort函数

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;
    }
}
最佳答案

How common doing something like this is?

参数化的比较器?不是很常见.通常,事物根据其自身的属性进行排序.

Is it considered a good design?

是的,如果要按与参考位置的距离对位置进行排序,那么使用参数化的“比较器”似乎是实现此目的的一种好方法.

但是,我可以看到我不喜欢的一件事.在抽奖的情况下,您的SortHotelsByProximity实际上正在与POI(兴趣点?)进行“秘密”比较.

如果要将此逻辑移至第二个比较器:SortHotelsByPOI,它将更加清楚,并在以后为您提供更大的灵活性.您可以将比较器组合在一起,以使用方法thenComparing进行平局,如下所示:

hotels.sort(new SortHotelsByProximity().thenComparing(new SortHotelsByPOI()))

Assuming I get a user input which should change the logic of the
comparison between some objects,building a new wrapper class (with
the given parameters) would be considered as a better solution for
that matter?

我不知道“包装器类”的含义,但是如果您要的是根据用户输入动态构建比较器就可以了.

原文地址:https://www.jb51.cc/java/532915.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐