Casting an array of objects into an Integer array

What happened to the following code?

Object[] a = new Object[1]; Integer b=1; a[0]=b; Integer[] c = (Integer[]) a; 

The last line of code has the following error:

An exception in the stream "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be applied to [Ljava.lang.Integer;

+56
java casting
Jul 12 '09 at 3:14
source share
4 answers

Ross, you can also use Arrays.copyof () or Arrays.copyOfRange ().

 Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class); Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class); 

Here's the reason for ClassCastException a ClassCastException is that you cannot treat an Integer array as an Object array. Integer[] is a subtype of Object[] , but Object[] not Integer[] .

And the following also will not give ClassCastException .

 Object[] a = new Integer[1]; Integer b=1; a[0]=b; Integer[] c = (Integer[]) a; 
+81
Nov 21 '11 at 11:59 a.m.
source share
β€” -

You cannot allocate an Object array to an Integer array. You must skip all elements of a and drop each separately.

 Object[] a = new Object[1]; Integer b=1; a[0]=b; Integer[] c = new Integer[a.length]; for(int i = 0; i < a.length; i++) { c[i] = (Integer) a[i]; } 

Edit: I believe the rationale for this limitation is that when casting, the JVM wants to provide type safety at runtime. Since the Objects array can be something other than Integers , the JVM would have to do what the above code does (look at each element separately). The language developers decided that they did not want the JVM to do this (I'm not sure why, but I'm sure this is a good reason).

However, you can apply an array of subtypes to an array of supertypes (for example, Integer[] to Object[] )!

+17
Jul 12 '09 at 3:17
source share

Or follow these steps:

 ... Integer[] integerArray = new Integer[integerList.size()]; integerList.toArray(integerArray); return integerArray; } 
+11
Jul 26 '11 at 11:33
source share
 java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; 

You are trying to pass an array of objects for conversion to an Integer array. You cannot do this. This type of downcast is not allowed.

You can create an Integer array and then copy each value of the first array to the second array.

+4
Jul 12 '09 at 11:59
source share



All Articles