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 String
s (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();
Author by
Vicky
A software developer with zeal to learn new things all the time!!
Updated on November 18, 2020Comments
-
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 over 12 yearschanging currencies to List<String[]> threw java.lang.ClassCastException: java.lang.String incompatible with [Ljava.lang.String;
-
dbf over 12 yearsI mean not List<String[]>, but List<String>, because looks like your query returns one column, that is converted to list of strings.
-
Donal Fellows over 12 yearsAnd the result is definitely not a list of arrays of anything.
-
Vicky over 12 yearsSo 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 over 12 yearsIt 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 over 12 yearsi am not sure what the getResultList returns. I would assume its a List. Or does it return Object Array?
-
Vicky over 12 yearsThanks!! 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 over 12 yearsIt depends on the concrete implementation of your EntityManager, but it certainly looks that way.