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?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值