首页 > 解决方案 > 两个代码片段中哪一个更适合用于比较器?

问题描述

我想知道按照最佳实践实施比较器方法的最佳方法是什么?

我实现了一个,其他人实现了另一个。

请任何关于哪个更合适的建议都会很棒!

public class Product
{
public Product (String name, int weight) {

        this.name = name;
        this.weight = weight; 

    }

    public static final Comparator<Product> BY_WEIGHT = new Comparator<Product>() {

        public int compare(final Product weight1, final Product weight2) {

            return weight1.weight - weight2.weight;
        }
    };

    public String getName() {
        return name;
    }

    public int getWeight() {
        return weight;
    }
}

或者

public class Product {

    private final String name;
    private final int weight;

    public Product (String name, int weight) {

        this.name = name;
        this.weight = weight; 

    }

    public static final Comparator<Product> BY_WEIGHT = new Comparator<Product>(){

        public int compare (final Product p1, final Product p2) {

            return Integer.compare(p1.getWeight(), p2.getWeight());
        }

    };

    public String getName() {
        return name;
    }

    public int getWeight() {
        return weight;
    }

标签: java

解决方案


return weight1.weight - weight2.weight实现存在数字溢出的风险,因此它可能对某些输入行为不端(尽管假设Product' 的权重不会接近Integer.MAX_VALUEor可能是安全的Integer.MIN_VALUE,因此实现可能会正常工作)。

通常Integer.compare(p1.getWeight(), p2.getWeight())是更好的实现,因为它不能溢出(它返回(x < y) ? -1 : ((x == y) ? 0 : 1))。


推荐阅读