Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCastException, casting Integer to Double

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

like image 580
Khuba Avatar asked Apr 06 '11 12:04

Khuba


People also ask

Can you cast an Integer to a double?

We can convert int value to Double object by instantiating Double class or calling Double. valueOf() method.

How do you turn a number into a double?

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.

Can you cast an int to a byte?

An int value can be converted into bytes by using the method int. to_bytes().


2 Answers

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.

like image 142
Andreas Dolk Avatar answered Sep 23 '22 13:09

Andreas Dolk


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.

like image 28
Jon Skeet Avatar answered Sep 24 '22 13:09

Jon Skeet