首页 > 解决方案 > 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 可能会溢出。但是编译器说我的代码有问题。我不知道为什么。任何人都可以帮助我。

标签: java

解决方案


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

推荐阅读