PriorityQueue(Java),用Long覆盖比较器

问题描述 投票:-4回答:1
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可能会溢出。但编译器说我的代码有问题。我不知道为什么。任何人帮助我PLZ。

java
1个回答
6
投票

Comparator.compare方法必须返回int。这就是界面定义方法的方式:

public int compare(Point a, Point b) {

我假设您认为必须返回long,因为减法会产生long类型的表达式。首先,不要使用减法,以防它们溢出。

相反,使用Long.compare,它返回int

return Long.compare(b.x, a.x);
return Long.compare(disB, disA);
© www.soinside.com 2019 - 2024. All rights reserved.