class cast exception: java.lang.String incompatible with [Ljava.lang.Object;

36,536

I'm not sure why you are thinking that the Query would return a list of Object arrays.

The query will most likely return a list of Strings (unless the Currency entity contains a Currency object, in which case I'd revisit the data design), so operating under the assumption that this is a scalar query, your code can be simplified to:

String currencySql = "select C.Currency from Currency C";
Query currencyQuery = this.em.createQuery(currencySql);

List<String> currencyList = (List<String>) currencyQuery.getResultList();
Share:
36,536
Vicky
Author by

Vicky

A software developer with zeal to learn new things all the time!!

Updated on November 18, 2020

Comments

  • Vicky
    Vicky over 3 years

    What is wrong with below code ?

    List<Object[]> currencies = null;
    List<String> currencyList = new ArrayList<String>();
    
    //code to fetch currency
    String currencySql = "select C.Currency from Currency C";
    Query currencyQuery = this.em.createQuery(currencySql);
    
    currencies = currencyQuery.getResultList();
    
    for (Object[] currency : currencies) {    //getting runtime error here
       for (int i = 0; i < currency.length; i++) {
                currencyList.add(currency[i].toString());
            }
        }
    

    Getting runtime error in first line of for loop as: java.lang.ClassCastException: java.lang.String incompatible with [Ljava.lang.Object;

    The code compiles alright.

    What is the issue ?

  • Vicky
    Vicky over 12 years
    changing currencies to List<String[]> threw java.lang.ClassCastException: java.lang.String incompatible with [Ljava.lang.String;
  • dbf
    dbf over 12 years
    I mean not List<String[]>, but List<String>, because looks like your query returns one column, that is converted to list of strings.
  • Donal Fellows
    Donal Fellows over 12 years
    And the result is definitely not a list of arrays of anything.
  • Vicky
    Vicky over 12 years
    So is it that hibernate decides from the SQL whether it will return list of strings or list of objects based on the type of things returned ???
  • Donal Fellows
    Donal Fellows over 12 years
    It knows the types. It knows how many values there are in each row. It says “one value per row; row value is that value” rather than wastefully putting it inside an array of length 1.
  • Sid Malani
    Sid Malani over 12 years
    i am not sure what the getResultList returns. I would assume its a List. Or does it return Object Array?
  • Vicky
    Vicky over 12 years
    Thanks!! So if the query is for several columns, in that case getResultList will return list of Object arrays. But in this case it was just one column, which was String, it returned a list of Strings. Correct ???
  • beny23
    beny23 over 12 years
    It depends on the concrete implementation of your EntityManager, but it certainly looks that way.