gpt4 book ai didi

java - 两个代码片段中哪一个更适合用于比较器?

转载 作者:行者123 更新时间:2023-11-29 08:26:18 25 4
gpt4 key购买 nike

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

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

请提供更合适的建议!

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;
}

最佳答案

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

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

关于java - 两个代码片段中哪一个更适合用于比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52647391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com