Java 在两个代码片段中,哪一个更适合作为比较器实现?

Java 在两个代码片段中,哪一个更适合作为比较器实现?,java,Java,我想知道按照最佳实践实现comparator方法的最佳方式是什么 我实现了一个,其他人实现了另一个 请提供任何更合适的建议 public class Product { public Product (String name, int weight) { this.name = name; this.weight = weight; } public static final Comparator<Product> BY_WEI

我想知道按照最佳实践实现comparator方法的最佳方式是什么

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

请提供任何更合适的建议

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;
    }
}
公共类产品
{
公共产品(字符串名称、整数权重){
this.name=名称;
重量=重量;
}
公共静态最终比较器,按重量=新比较器(){
公共整数比较(最终产品权重1,最终产品权重2){
返回权重1.weight-权重2.weight;
}
};
公共字符串getName(){
返回名称;
}
公共整数getWeight(){
返回重量;
}
}

公共类产品{
私有最终字符串名;
私人最终整数权重;
公共产品(字符串名称、整数权重){
this.name=名称;
重量=重量;
}
公共静态最终比较器,按重量=新比较器(){
公共整数比较(最终产品p1、最终产品p2){
返回整数.compare(p1.getWeight(),p2.getWeight());
}
};
公共字符串getName(){
返回名称;
}
公共整数getWeight(){
返回重量;
}

返回weight1.weight-weight2.weight实现有数字溢出的风险,因此它可能会对某些输入行为不当(尽管可以安全地假设
产品
的重量不会接近
整数.MAX\u值
整数.MIN\u值
,因此实现可能会正常工作)


一般来说,
Integer.compare(p1.getWeight(),p2.getWeight())
是更好的实现,因为它不会溢出(它返回
(x
)。

返回权重1.weight-weight 2.weight
实现有数字溢出的风险,因此它可能会对某些输入产生错误行为(尽管可以安全地假设
产品
的重量不会接近
整数.MAX\u值
整数.MIN\u值
,因此实现可能会正常工作)


一般来说,
Integer.compare(p1.getWeight(),p2.getWeight())
是更好的实现,因为它不会溢出(它返回
(x
)。

第二个选项,原因@Eran已经提到过

此版本使用内置比较器:

    public static final Comparator<Product> BY_WEIGHT =
            Comparator.comparingInt(Product::getWeight);
公共静态最终比较器(按重量)=
Comparator.comparingInt(产品::getWeight);

第二个选项,因为@Eran已经提到了这个原因

此版本使用内置比较器:

    public static final Comparator<Product> BY_WEIGHT =
            Comparator.comparingInt(Product::getWeight);
公共静态最终比较器(按重量)=
Comparator.comparingInt(产品::getWeight);

@Glains是的,第二个实现也有更好的命名。@Glains是的,第二个实现也有更好的命名。