I've spent hours on this bug, this is a very strange behavior for me :
Here is my code :
Map<String, Float> myMap = myService.calculateData(DateTime startDate, DateTime endDate);
if (!myMap.isEmpty()) {
Double value1 = myMap.get("key1").doubleValue();
}
In the debugger, everything works fine, I can see all the values of myMap and I can get the value of value1 as a Double.
But then, IntelliJ throws the error :
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float
I tried replacing Double value1 = myMap.get("key1").doubleValue();
with : Float value1 = myMap.get("key1");
and I get the exact same error, even though I'm not using any Double !
Also I don't understand why it says Double cannot be cast to Float, when I'm actually trying to convert a Float into a Double, so it's the other way around.
UPDATE : to answer to Louis and Andreas suggestions, myMap.get("key1").getClass() gives me Double , myMap.get("key1") instanceof Double equals true and myMap.get("key1") instanceof Float equals false.
I get the error on the line Double value1 = myMap.get("key1").doubleValue(); or on Float value1 = myMap.get("key1");
1 Answer 1
This would be a normal symptom for some corruption in how the Map from myService.calculateData was constructed in the first place; it's not really a Map<String, Float>, it's got Doubles in it. That's usually an indication that there were some suppressed unsafe casts or rawtypes.
The cast to Float would be implicitly inserted into the map.get("key1") call at compile time, as part of how generics are normally implemented.
3 Comments
System.out.println(myMap.get("key1").getClass()).myMap.get("key1").getClass() gives me Double , myMap.get("key1") instanceof Double equals true and myMap.get("key1") instanceof Float equals false. So can the problem be fixed in myService.calculateData only ? Not in my code ?myService.calculateData . You saved me some hours of debugging ! :)
Float value1 = myMap.get("key1");AFAIK cannot throw that exception.Float value1 = myMap.get("key1");can throw that exception... this is driving me crazy ! I'll check what happens inmyService.calculateDataand if that doesn't work, I'll post the entire stack trace.