ClassCastException, casting Integer to Double

后端 未结 10 1981
我寻月下人不归
我寻月下人不归 2020-12-24 05:33
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

10条回答
  •  遥遥无期
    2020-12-24 05:56

    The code posted in the question is obviously not a a complete example (it's not adding anything to the arraylist, it's not defining i anywhere).

    First as others have said you need to understand the difference between primitive types and the class types that box them. E.g. Integer boxes int, Double boxes double, Long boxes long and so-on. Java automatically boxes and unboxes in various scenarios (it used to be you had to box and unbox manually with library calls but that was deemed an ugly PITA).

    http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

    You can mostly cast from one primitive type to another (the exception being boolean) but you can't do the same for boxed types. To convert one boxed type to another is a bit more complex. Especially if you don't know the box type in advance. Usually it will involve converting via one or more primitive types.

    So the answer to your question depends on what is in your arraylist, if it's just objects of type Integer you can do.

    sum = ((double)(int)marks.get(i));
    

    The cast to int will behind the scenes first cast the result of marks.get to Integer, then it will unbox that integer. We then use another cast to convert the primitive int to a primitive double. Finally the result will be autoboxed back into a Double when it is assigned to the sum variable. (asside, it would probablly make more sense for sum to be of type double rather than Double in most cases).

    If your arraylist contains a mixture of types but they all implement the Number interface (Integer, Short, Long, Float and Double all do but Character and Boolean do not) then you can do.

    sum = ((Number)marks.get(i)).doubleValue();
    

    If there are other types in the mix too then you might need to consider using the instanceof operator to identify them and take appropriate action.

提交回复
热议问题