简体   繁体   中英

Error convert BigDecimal to int

I have the following situation:

List<BigDecimal> nvs = servSuperlivelloDAO.findNetworkVersion(year, daynumber);
int[] res = new int[nvs.size()];
for (int i = 0; i < nvs.size(); i++) {
    res[i] = nvs.get(i).intValue();
}

transforming BigDecimal to int gives this error:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.math.BigDecimal

I don't understand why I have a Integer in BigDecimal list.

i guess the problem is in the fist line

List<BigDecimal> nvs = servSuperlivelloDAO.findNetworkVersion(year, daynumber);

Try debugging the findnetworkVersion() method. And check the return type of that method. (is it really List of BigDecimal?).

I think that the DAO method : servSuperlivelloDAO.findNetworkVersion(year, daynumber) returned an int instead of a BigDecimal . Check it !

Here is an example where the BigDecimal was casted to int without any error:

package test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<BigDecimal>  list = new ArrayList<BigDecimal>();
        list.add(new BigDecimal(1));
        list.add(new BigDecimal(2));
        int arr[] =new int[list.size()];
        for(int i=0;i<list.size();i++)
        {
            arr[i] = list.get(i).intValue();
            System.out.println(arr[i]);
        }

    }
}

If Sasha's suggestion is correct, you can probably solve it by declaring nvs List<? extends Number> nvs List<? extends Number> nvs (I haven't tested).

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