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.

1
  • What is Pair? Is that a standard class? Commented May 15, 2022 at 20:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the OP is expecting that the declaration PriorityQueue<Pair<Integer, Double>> will force the int to a Double when new Pair is executed. But I'm not 100% sure that's what they're asking about either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.