15

I am trying to compute few calculations for my project and I get following java.lang.ClassCastException for
y2= (double) molWt[x];

molWt and dist are two array of type Number and double respectively.

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

public Double calcData(Number[] molWt, Double[] dist, String unk) {
        Double y2,y1, newY = null;
        Double x1,x2;

        Double unkn = Double.parseDouble(unk.toString());
        Double prev=0d;
        Double slope;


        for (int x = 0; x < dist.length; x++)
            if (unkn > prev && unkn < dist[x]) {
                y2 = (double) molWt[x];
                y1 = (double) molWt[x - 1];

                x2 = dist[x];
                x1 = dist[x - 1];

                slope = ((y2 - y1) / (x2 - x1));

                newY = slope * (unkn - x1) + y1;


            } else {
                prev = dist[x];
            }

        return newY;
    }
3
  • Well clearly molWt has at least one Integer in it. Is that a surprise? What is your actual question?
    – Radiodef
    Commented Apr 11, 2016 at 19:05
  • 3
    I can't see why you are using Number at all. Both arrays should be double[]. In my opinion, Number is completely useless. Commented Apr 11, 2016 at 19:08
  • 2
    Followup to comment by @PaulBoddington, why are you using boxed Double instead of primitive double? Can they be null? If so, your code will die a horrible death.
    – Andreas
    Commented Apr 11, 2016 at 19:15

2 Answers 2

33

Use Number.doubleValue():

y2 = molWt[x].doubleValue();

instead of trying to cast. Number cannot be cast to a primitive double.

2
  • 1
    You beat me to it by a second - hope you don't mind me adding the link!
    – Kenney
    Commented Apr 11, 2016 at 19:05
  • may throw runtime exception
    – Yin
    Commented Nov 6, 2019 at 4:57
2

you can use java.lang.Number.doubleValue() method to cast a number to a double object.

y2= molWt[x].doubleValue()

1
  • 4
    There's no point in posting an answer which merely duplicates another.
    – Radiodef
    Commented Apr 11, 2016 at 19:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.