ClassCastException, casting Integer to Double

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

    2 things to understand here -

    1) If you are casting Primitive interger to Primitive double . It works. e.g. It works fine.

    int pri=12; System.out.println((double)pri);

    2) if you try to Cast Integer object to Double object or vice - versa , It fails.

    Integer a = 1; Double b = (double) a; // WRONG. Fails with class cast excptn
    

    Solution -

    Soln 1) Integer i = 1; Double b = new Double(i);
    soln 2) Double d = 2.0; Integer x = d.intValue();
    

提交回复
热议问题