ArrayList marks = new ArrayList();
Double sum = 0.0;
sum = ((Double)marks.get(i));
Everytime I try to run my program, I get a ClassCastException th
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.
specify your marks:
List<Double> marks = new ArrayList<Double>();
This is called generics.
I think the main problem is that you are casting using wrapper class, seems that they are incompatible types.
But another issue is that "i" is an int so you are casting the final result and you should cast i as well. Also try using the keyword "double" to cast and not "Double" wrapper class.
You can check here:
Hope this helps. I found the thread useful but I think this helps further clarify it.
Integer x=10;
Double y = x.doubleValue();