java - 两个代码片段中哪一个更适合用于比较器?
问题描述
我想知道按照最佳实践实施比较器方法的最佳方法是什么?
我实现了一个,其他人实现了另一个。
请任何关于哪个更合适的建议都会很棒!
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_VALUE
or可能是安全的Integer.MIN_VALUE
,因此实现可能会正常工作)。
通常Integer.compare(p1.getWeight(), p2.getWeight())
是更好的实现,因为它不能溢出(它返回(x < y) ? -1 : ((x == y) ? 0 : 1)
)。
推荐阅读
- python - 如何创建一个布尔变量来确定第 i 天的价格是大于还是小于当天 (i-1)?
- java - 如何将导航抽屉的所有片段全屏显示?
- python - Python 彩票系统只有 6 个号码。我需要帮助,因为每个循环都只是添加到列表中。请帮忙
- javascript - 根据条件导入 React
- python - 用于最小二乘 kabsch 算法的 SCIPY 库示例 align_vectors
- c - 创建用户名函数如果根本没有输入怎么办?
- c# - 在 .NET Core Docker 映像中包含共享 C 库 (.SO)
- c# - 如何使用 Speex 正确移除回声消除?
- angular - Angular 库模块注入抽象类的相同服务实例
- postgresql - PostgreSQL:全文搜索未按预期工作