Search code examples
javaarraylistclasscastexceptionbigdecimal

BigDecimal incompatible with ArrayList, java ClassCastException


I'm debugging some code from a different project in Eclipse, and found that even though there is no error sign (just warning),

try
    {   
        conn =  dss.connect();

        System.out.println("[SIGN]: Executing first step ");

        beanResultVO = executeFirstStep(usuario,conn,parametros,beanResultadoVO);

        if(beanResultVO.getResultCode() == IConstants.SWS_MSG_SUCCESSFUL){                          

            BigDecimal someCoolVar = (BigDecimal)beanResultVO.getResultObject();
            System.out.println("[SIGN]: end of the first step ");
            ((ArrayList)beanResultVO.getResultObject()).add(someCoolVar); // <--- WARNING HERE: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized
            saveStuff(conn);
        }
    }
    catch(Exception e)
    {
        System.out.println("error: "+e); // THIS SHOWS -->  java.math.BigDecimal incompatible with java.util.ArrayList
        e.printStackTrace();            
        beanResultVO.setResultCode(IConstants.SWS_MSG_ERROR);
        undoStuff(conn);
    }

once I execute to the line with the warning it goes directly to an exception in the try/catch block, and shows this message:

java.math.BigDecimal incompatible with java.util.ArrayList

Here is beanResultVO :

public class BeanResultadoVO  extends BeanBase{
    private int resultCode = 0;
    private String resultMessage;
    private Object resultObject;


    public int getResultCode() {
        return resultCode;
    }
    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }
    public String getResultMessage() {
        return resultMessage;
    }
    public void setResultMessage(String resultMessage) {
        this.resultMessage = resultMessage;
    }
    public Object getResultObject() {
        return resultObject;
    }
    public void setResultObject(Object resultObject) {
        this.resultObject = resultObject;
    }
}

Now, I have tried to do

((ArrayList<BigDecimal>)beanResultVO.getResultObject()).add(someCoolVar);

getting different warning:

Unchecked cast from Object to ArrayList

But same exception


Solution

  • In Java all casting operations are checked. When cast cannot be done ClassCastException is thrown. In your example

    beanResultVO.getResultObject()
    

    is type of BigDecimal. BigDecimal cannot be cast to ArrayList because BigDecimal is not a superclass of ArrayList. If you need ArrayList you can use

    Arrays.asList(beanResultVO.getResultObject())
    

    or

    Collections.singletonList(beanResultVO.getResultObject())
    

    it returns the type you want, i.e.

    List<BigDecimal>