How to get a value from a List<Double> and store it into a double

I'm getting an Array from Firebase and I want to retrieve the values from the Array (I am able to print them successfully but I cannot store them into a double).

List<Double> weight = (List<Double>) data.get("Weight");
int weightLength = weight.size();
double currentWeight = (double) weight.get(weightLength-1);

I receive the following error:

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

Edit: I changed the List type from Double to Long and I am not able to get an output of "[60]". I have the value 60 stored in my Firebase Cloud Firestore

List<Long> weight = (List<Long>) data.get("Weight");
int weightLength = weight.size();
double currentWeight = weight.get(weightLength-1);

2 answers

  • answered 2020-11-20 11:57 Joop Eggen

    The problem is that long can be cast to double, but not Long. Two solutions:

    Leave long-to-double to the compiler, and just ensure long:

    double currentWeight = (long) weight.get(weightLength-1);
    

    Use that long, Long, int, Integer and all are Number, with conversion functions:

    double currentWeight = weight.get(weightLength-1).doubleValue();
    

    The latter is nicest IMHO.

    I saw that @fatma zehra güç gave this error, probably before the OP's edit.

  • answered 2020-11-20 12:00 Arvind Kumar Avinash

    data.get("Weight") returns List<Long> that you tried to cast to List<Double> which is not allowed e.g. the following code won't even pass compilation:

    List<Long> list = List.of(1L, 2L);
    List<Double> weight = (List<Double>) list;
    

    So, the solution is to declare weight of the type, List<Long> i.e.

    List<Long> weight = (List<Long>) data.get("Weight");
    

    Also, you do not need to cast a long explicitly to double i.e. the following line

    double currentWeight = (double) weight.get(weightLength-1);
    

    can be simply written without an explicit cast as

    double currentWeight = weight.get(weightLength - 1);