-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?

3
  • I also tried with Integer[] - did you try int[] array = (Integer[]) object; or Integer[] array = (Integer[]) object;? Only the latter should work. Commented Jul 28, 2016 at 11:01
  • Try to cast your list to object[] (List<Object[]>) Commented Jul 28, 2016 at 11:05
  • 4
    This post should have the answer to your question: stackoverflow.com/questions/1115230/… Commented Jul 28, 2016 at 11:06

1 Answer 1

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()

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.