英文:
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<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );
I keep getting this error:
PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((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 float
s 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<Point> minHeap = new PriorityQueue<Point>( (a,b) -> Float.compare(a.distance, b.distance));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论