Java ClasscastException混乱

发布于 2025-01-29 02:51:21 字数 624 浏览 2 评论 0原文

我有以下代码:

PriorityQueue<Pair<Integer, Double>> pq = 
      new PriorityQueue<>((v1, v2) -> (int)Math.floor(v1.getValue() - v2.getValue()));
pq.add(new Pair(1, 0));
Pair<Integer, Double> node = pq.poll();
double time = node.getValue();

最后一行会提出

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class
java.lang.Double (java.lang.Integer and java.lang.Double are in module 
java.base of loader 'bootstrap')

问题,如果我想用第二个语句替换第二个语句,

pq.add(new Pair(1, 0.0));

我想了解引擎盖下发生的事情,从而导致此例外。

I have the following code:

PriorityQueue<Pair<Integer, Double>> pq = 
      new PriorityQueue<>((v1, v2) -> (int)Math.floor(v1.getValue() - v2.getValue()));
pq.add(new Pair(1, 0));
Pair<Integer, Double> node = pq.poll();
double time = node.getValue();

The last line raises a

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class
java.lang.Double (java.lang.Integer and java.lang.Double are in module 
java.base of loader 'bootstrap')

The issue goes away if I replace the second statement with

pq.add(new Pair(1, 0.0));

I'd like to understand what is happening under the hood resulting in this exception.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小苏打饼 2025-02-05 02:51:21

int可以施放到double,但是Integer不能将其施放到double

当您实例化Pair&lt; integer时,double&gt;,这两个int值都被自动介绍到integer。但是您需要的是整数double

An int can be cast to a double, but an Integer can't be cast to a Double.

When you instantiate your Pair<Integer, Double>, both int values that you're passing are getting autoboxed to Integer. But what you needed was an Integer and a Double.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文