Search code examples
javacastingclasscastexception

How to resolve exception java.lang.ClassCastException: java.math.BigDecimal cannot be cast to [Ljava.lang.Object; in java


In my code query is working fine but at the time of iteration it throws this error.

My code here:

Session session = null;
try{
    Query qu=session.createSQLQuery("select plot_no from house_details where type='duplex'");
    List<Long> li =  qu.list();
    System.out.println("---li---"+li.toString());
    for (Iterator itr = li.iterator(); itr.hasNext();) {
        String plotNo = itr.next().toString();

        if(plotNo.equals("501") || plotNo.equals("520") || plotNo.equals("601"){
            System.out.println("---if---");
            //code here
        }
        else{
            System.out.println("---else---");
            Query qu1 = session.createSQLQuery("select distinct name,houseno from house_details");
            List li1 =  qu1.list();
            for (Iterator itr1 = li.iterator(); itr1.hasNext();) {
                Object[] obj = (Object[]) itr1.next();
                String houseName = (String) obj[0];
                String houseNo = (String) obj[1];
                System.out.println("---houseName--->"+houseName);
            }
    }
}catch(Exception e){
   e.printStackTrace();

}finally {
   if(session!=null){
    session.close();
   }
}

output:

---li---[501, 0, 101, 101, 114]
---else---
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to [Ljava.lang.Object;

it shows error in Object[] obj = (Object[]) itr1.next(); line.

What's wrong in my code?


Solution

  • First, the cast: you are treating an iterator over the list li as if it were an iterator over a list of arrays, while in fact it is an iterator over a list of BigDecimals. It's li1 that you should be iterating:

    for (Iterator itr1 = li1.iterator() ; itr1.hasNext() ; )
    //                     ^
    

    Another error happens early on:

    List<Long> li =  qu.list();
    

    it should be

    List<BigDecimal> li =  qu.list();
    

    because objects inside the list returned by your query are of type BigDecimal, as confirmed by the failing cast.