-2

I am reading a row from the database using JPA, which provides an Object with three int values.

Eclipse debugger

I am now trying to cast this object to an int[] array, which throws an ClassCastException and says:

Ljava.lang.Object; cannot be cast to [I

This is my code:

try {
    utx.begin();
} catch (NotSupportedException e) {
    e.printStackTrace();
} catch (SystemException e) {
    e.printStackTrace();
}
Query q = em.createNativeQuery("SELECT * FROM mytable");
List<Object> objectList = q.getResultList();

for (int i = 0; i < objectList.size(); i++) {
    Object object = objectList.get(i);
    int[] array = (int[]) object;
}

I also tried with Integer[]. Same exception.

Does someone see the problem? How can I cast it?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
John
  • 795
  • 3
  • 15
  • 38
  • `I also tried with Integer[]` - did you try `int[] array = (Integer[]) object;` or `Integer[] array = (Integer[]) object;`? Only the latter should work. – Eran Jul 28 '16 at 11:01
  • Try to cast your list to object[] (List) – Manu AG Jul 28 '16 at 11:05
  • 4
    This post should have the answer to your question: http://stackoverflow.com/questions/1115230/casting-object-array-to-integer-array-error – anaBad Jul 28 '16 at 11:06

1 Answers1

0

Just as noted , there is a difference in int[] and Integer[]. As noted by @anabad you can follow the other SO post. To cast it to Integer[] is a one liner and for int[] you will need a loop

Object[] objectArray = new Object[] { new Integer("32"), new Integer("11"), new Integer("0") };
int[] integers = new int[objectArray.length];

Integer[] objectIntArray = Arrays.copyOf(objectArray, objectArray.length,Integer[].class);


for (int i = 0; i < objectArray.length; i++) {
    integers[i] = (int) objectArray[i];// works from java 7 , else
                                        // use
                                        // Integer.parseInt(objectArray[i].toString()

}
Ramachandran.A.G
  • 4,788
  • 1
  • 12
  • 24