JAVA优先队列(PriorityQueue)比较器不接受浮点数。

huangapple go评论58阅读模式
英文:

JAVA PriorityQueue comparator not accepting float

问题

我有以下的类:

    int x;
    int y;
    float distance;
    
    public Point(int x, int y, float distance){
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}

在我的主程序中,我有以下代码行:

PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );

我一直在收到这个错误:

        PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );
                                                                                              ^
    可能会丢失从float到int的转换```
------------------------------------------------------------------------------------

我不知道为什么不接受我的比较器方法。有任何想法吗?提前感谢。

<details>
<summary>英文:</summary>

I have the following class:
------------------------------------------------------------------------------------
```class Point{
    int x;
    int y;
    float distance;
    
    public Point(int x, int y, float distance){
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}

On my main program I have this line:

PriorityQueue&lt;Point&gt; minHeap = new PriorityQueue&lt;Point&gt;( (a,b) -&gt; ((float) a.distance - (float) b.distance) );

I keep getting this error:

        PriorityQueue&lt;Point&gt; minHeap = new PriorityQueue&lt;Point&gt;( (a,b) -&gt; ((float) a.distance - (float) b.distance) );
                                                                                              ^
    possible lossy conversion from float to int```
------------------------------------------------------------------------------------

I dont know why is not accepting my comparator method. Any ideas? thanks in advance.

</details>


# 答案1
**得分**: 4

那是因为您所定义的 `compare` 方法返回一个 `int`,但由于您在两个 `float` 之间进行了操作,编译器告诉您可能会丢失一些数据(实际上确实会丢失,所有小数部分),但您实际上并不关心,因为这只是一个比较器。

您可以在以下代码中使用 [`Float.compare(f1, f2)`][1]:

```java
PriorityQueue<Point> minHeap = new PriorityQueue<Point>((a, b) -> Float.compare(a.distance, b.distance));
英文:

That's because the compare method you're defining returns an int, but since you're getting an int with an operation between floats the compiler tells you some data might get lost (it actually will, all the decimals, but you don't really care since it's just a comparator).

You could use Float.compare(f1, f2) in

PriorityQueue&lt;Point&gt; minHeap = new PriorityQueue&lt;Point&gt;( (a,b) -&gt; Float.compare(a.distance, b.distance));

huangapple
  • 本文由 发表于 2020年5月30日 23:24:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/62104608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定