Converting Object[] array to List in java
Solution 1
Try with ArrayList:
ArrayList<Object> list = new ArrayList(Arrays.asList(yourArray));
and then add whatever element you want to the list using
list.add(newItem)
Solution 2
The getResultList
method do return a List<Object[]>
if you are for example querying multiple entities and the result cannot be mapped automatically onto an existing entity class.
To avoid this you may consider a constructor expression in your JPA query like this:
Query query = getEntityManager()
.createQuery("SELECT NEW my.Foo(a.id, b.somethingelse) FROM --- ");
The getResultList()
method now will return a List<Foo>
and you do not run into the problem that you have mentioned.
Randy
Updated on June 12, 2020Comments
-
Randy almost 4 years
on a primefaces 3.5 form I created with a datatable the rowKey value is not being returned as a List, therefore I am getting the following error:
JBWEB000309: type JBWEB000066: Exception report JBWEB000068: message For input string: "foreignPartyId" JBWEB000069: description JBWEB000145: The server encountered an internal error that prevented it from fulfilling this request. JBWEB000070: exception javax.servlet.ServletException: For input string: "foreignPartyId" javax.faces.webapp.FacesServlet.service(FacesServlet.java:606) JBWEB000071: root cause java.lang.NumberFormatException: For input string: "foreignPartyId" java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) java.lang.Integer.parseInt(Integer.java:492) java.lang.Integer.parseInt(Integer.java:527) javax.el.ListELResolver.toInteger(ListELResolver.java:407) javax.el.ListELResolver.getValue(ListELResolver.java:199) ...
I know the reason is because I am trying to populate the datatable with values from an Object[] array, rather than a List. The Object[] array is actually values from getResultList() using the createNativeQuery method to query an Oracle database.
My question is: How do I convert the values in the Object[] array into a List so that the datatable is populated?
I have tried using the Arrays.toList() method, and then iterating through that adding the values to a list, but I understand that that simply returns a fixed size list of the backed array. It does not return a List of values.
Any help would be greatly appreciated. My apologies if I have not provided enough detail. Thank you.