ClassCastException, casting Integer to Double

后端 未结 10 1971
我寻月下人不归
我寻月下人不归 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:39

    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.

提交回复
热议问题