ClassCastException, casting Integer to Double

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

    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.

    0 讨论(0)
  • 2020-12-24 06:00

    specify your marks:

    List<Double> marks = new ArrayList<Double>();
    

    This is called generics.

    0 讨论(0)
  • 2020-12-24 06:04

    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:

    • Java Docs Cast Exception
    • Stack Overflow Thread about ClassCastException

    Hope this helps. I found the thread useful but I think this helps further clarify it.

    0 讨论(0)
  • 2020-12-24 06:06
    Integer x=10;
    Double y = x.doubleValue();
    
    0 讨论(0)
提交回复
热议问题