简体   繁体   中英

Java cast double to long exception

1- long xValue = someValue;

2- long yValue = someValue;

3- long otherTolalValue = (long)(xValue - yValue);

That line of code give me the following exception:

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

  • Update :

code piece:

StackedBarChart<String,Number> sbc = new StackedBarChart<String,Number>();

XYChart.Series<String, Number> series = new XYChart.Series<String, Long>();
series.getData.add(new XYChart.Data<String, Number>("X1",150));
series.getData.add(new XYChart.Data<String, Number>("X2",50));
sbc.getData.add(series);
long dif = getDif(sbc);

long getDif(XYChart barChart){
XYChart.Series series = (XYChart.Series).getData().get(0);
// X1 at zero position i dont have to use iIterator now.
XYChart.Data<String, Long> seriesX1Data = series.getData().get(0);
XYChart.Data<String, Long> seriesX2Data = series.getData().get(1);

long x1Value = seriesX1Data.getYValue();
long x2Value = seriesX1Data.getYValue();
// line - 3 - exception on the next line
// -4- long value = (x1Value) - (x2Value);
long value = (long)(x1Value) - (long)(x2Value);
return value;
}
  • After debug i found that.

seriesX1Data,seriesX2Data contains double values as the passed chart has Number type but getYvalue() return long that is why program crash at runtime with that exception but when i cast in line why cast not succeed. i think that compiler see that the type already long !.

long xValue = (long)someValue;
// or : 
long yValue = new Double(someValue).longValue();

long otherTolalValue = xValue - yValue;

But keep in mind that you will loose precision.

It's impossible

long xValue = someValue;
long yValue = someValue;
long otherTolalValue = (long)(xValue - yValue);

neither of the 3 lines can produce java.lang.ClassCastException

Assuming someValues is Double,

Double someValue = 0.0;

it would give compile error: Type mismatch: cannot convert Double to long

I don't really understand why your code fail, but the following also works fine.

    public class CastingDoubleToLongTest {

      @Test
      public void testCast(){
        double xValue = 12.457;
        double yValue = 9.14;

        long diff = new Double(xValue - yValue).longValue();

        Assert.assertEquals(3, diff);
      }
   }

Presumably someValue is a double . To assign it to a long you need to cast it:

long xValue = (long) someValue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM