There is no way to cast an Object[]
to an int[]
, even if all the objects in the source array are Integer
objects (like your example), because all the values need to be unboxed, not just cast.
Object[] A1 = {1,2,3,4};
That statement is actually auto-boxing the 4 integer literals for you, so the compiler is turning it into this:
Object[] A1 = new Object[4];
A1[0] = Integer.valueOf(1);
A1[1] = Integer.valueOf(2);
A1[2] = Integer.valueOf(3);
A1[3] = Integer.valueOf(4);
As can be seen from this decompilation:
public static void main(java.lang.String[]) throws java.lang.Exception;
Code:
0: iconst_4
1: anewarray #3 // class java/lang/Object
4: dup
5: iconst_0
6: iconst_1
7: invokestatic #19 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
10: aastore
11: dup
12: iconst_1
13: iconst_2
14: invokestatic #19 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
17: aastore
18: dup
19: iconst_2
20: iconst_3
21: invokestatic #19 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
24: aastore
25: dup
26: iconst_3
27: iconst_4
28: invokestatic #19 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
31: aastore
32: astore_1
33: return
Any solution must do the traversing of every item to unbox the values, whether explicitly or implicitly.
Various ways to do that:
// Using cast to specific type and auto-unboxing (object cast)
int[] arr1 = new int[A1.length];
for (int i = 0; i < A1.length; i++)
arr1[i] = (Integer)A1[i];
// Using cast to specific type and explicit unboxing
int[] arr2 = new int[A1.length];
for (int i = 0; i < A1.length; i++)
arr2[i] = ((Integer)A1[i]).intValue();
// Using cast to more generic type and value extraction
int[] arr3 = new int[A1.length];
for (int i = 0; i < A1.length; i++)
arr3[i] = ((Number)A1[i]).intValue();
// Using Java 8 streams with method references
int[] arr4 = Arrays.stream(A1)
.map(Integer.class::cast)
.mapToInt(Integer::intValue)
.toArray();
// Using Java 8 streams with lambda expression with auto-unboxing (primitive cast)
int[] arr5 = Arrays.stream(A1)
.mapToInt(o -> (int)o)
.toArray();