ArrayList marks = new ArrayList(); Double sum = 0.0; sum = ((Double)marks.get(i));
Everytime I try to run my program, I get a ClassCastException that states: java.lang.Integer cannot be cast to java.lang.Double
We can convert int value to Double object by instantiating Double class or calling Double. valueOf() method.
Conversion using valueOf() method of Double wrapper class Double wrapper class valueOf() method converts int value to double type. It returns the Double-object initialized with the provided integer value. Here, d = variable to store double value after conversion to double data type.
An int value can be converted into bytes by using the method int. to_bytes().
We can cast an int
to a double
but we can't do the same with the wrapper classes Integer
and Double
:
int a = 1; Integer b = 1; // inboxing, requires Java 1.5+ double c = (double) a; // OK Double d = (Double) b; // No way.
This shows the compile time error that corresponds to your runtime exception.
Well the code you've shown doesn't actually include adding any Integers to the ArrayList
- but if you do know that you've got integers, you can use:
sum = (double) ((Integer) marks.get(i)).intValue();
That will convert it to an int
, which can then be converted to double
. You can't just cast directly between the boxed classes.
Note that if you can possibly use generics for your ArrayList
, your code will be clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With