加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java-具有字段的比较器类

发布时间:2020-12-14 19:29:24 所属栏目:Java 来源:网络整理
导读:在一个使用实现了Comparator接口的类的项目中,为了在一些可比较的对象之间进行比较,我注意到我可以设计实现Comparator接口的类.与字段进行接口,然后重写compare()函数,并将类的字段用于比较函数逻辑. 所以我必须像这样调用sort函数: Collections.sort(someA

在一个使用实现了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?

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读