Search code examples
javaandroid-studioclasscastexception

ClassCastException when both the variables are floats in android studio


My code has an ArrayList defined as:

ArrayList<Float> dummyArray = new ArrayList();

and a float variable defined as:

float smoothedValue;

The code is executed as follows:

 if(x==1  && dummyArray.size()>1) //x is an int
{
smoothedValue =  dummyArray.get(dummyArray.size()-1); //Error here
}

I get the following error:

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

The variables are defined inside the same method (a private method in a class) and both are floats (the elements of ArrayList are also float). Why am I getting this error? Have I done something wrong?

Thank you.


Solution

  • The real problem was that the FLOAT was forcing the getValue cast to use DOUBLE. After digging more, I got the solution. I used the following approach:

    Float.valueOf(String.valueOf(double_variable));
    

    For example:

    smoothedValue = Float.valueOf(String.valueOf(dummyArray.get(dummyArray.size()-1)));