Java ClasscastException混乱
我有以下代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
int
可以施放到double
,但是Integer
不能将其施放到double
。当您实例化
Pair&lt; integer时,double&gt;
,这两个int
值都被自动介绍到integer
。但是您需要的是整数
和double
。An
int
can be cast to adouble
, but anInteger
can't be cast to aDouble
.When you instantiate your
Pair<Integer, Double>
, bothint
values that you're passing are getting autoboxed toInteger
. But what you needed was anInteger
and aDouble
.