Type of casting Number in double

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

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

java.lang.ClassCastException: java.lang.Integer cannot be dropped 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; } 
+5
source share
3 answers

Use Number.doubleValue () :

 y2 = molWt[x].doubleValue(); 

instead of trying to complete a throw. Number cannot be passed to the primitive double .

+11
source

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

y2 = molWt [x] .doubleValue ()

+1
source

Double and Number are boxed primitives. They are used, so we can process primitives such as objects. If you can use primitives then do it. They are much less memory and make calculations much faster.

In this case, if you want to convert Number to Double , you will need to make two throws. One to make Integer in int , and the other to make int in Double .

 y2 = (double) (int) molWt[x]; 

Another compiler will also add a compiler. Equalization Alignment:

 y2 = (Double) (double) (int) molWt[x]; 

However, you should just use the whole primitives, because this casting will kill your performance.

+1
source

Source: https://habr.com/ru/post/1246895/


All Articles