java - PriorityQueue (Java),用 Long 覆盖比较器
问题描述
PriorityQueue<Point> pq = new PriorityQueue(10, new Comparator<Point>(){
public long compare(Point a, Point b) {
long disA = (a.x - origin.x) * (a.x - origin.x) + (a.y - origin.y) * (a.y - origin.y);
long disB = (b.x - origin.x) * (b.x - origin.x) + (b.y - origin.y) * (b.y - origin.y);
if (disA == disB) {
return (long)(a.x - b.x);
}
else {
return disA - disB;
}
}
});
我正在编写 PriorityQueue 并覆盖 Comparator,但我需要使用 Long 而不是 int。因为 disA 和 disB 可能会溢出。但是编译器说我的代码有问题。我不知道为什么。任何人都可以帮助我。
解决方案
该Comparator.compare
方法必须返回int
。这就是接口定义方法的方式:
public int compare(Point a, Point b) {
我假设您认为您必须返回long
,因为减法产生 type 的表达式long
。一方面,不要使用减法,以防它们溢出。
相反,使用Long.compare
,它返回int
:
return Long.compare(b.x, a.x);
return Long.compare(disB, disA);
推荐阅读
- javascript - 在postgres中选择x,其中y等于z
- java - 无法从硒的下拉菜单中选择选项(尝试了所有方法)
- express - 将代码推送到生产环境时保持服务器网关处于活动状态
- c - Scanf 在我的汇编程序中不断出现段错误
- html - 关于 IE10 浏览器 (Window7) 中的`Flex Layout`
- ssis - SSIS - 如何在平面文件源和 OLE DB 目标之间添加 sql 列?
- .net-core - Blazor 和路由页面
- javascript - Jquery,自动完成值未显示在模态视图上
- vb.net - 运行 CMD 最小化/隐藏
- mongodb - 在 mongoDB 中按日期分组,同时计算其他字段