Casting Object Array to Integer Array: ClassCastException Issue
When attempting to cast an Object array to an Integer array, a ClassCastException error may arise. This occurs because, despite Integer[] being a subtype of Object[], the array of objects cannot be directly assigned to an array of integers.
Consider the following code:
Object[] a = new Object[1]; Integer b=1; a[0]=b; Integer[] c = (Integer[]) a;
This code generates a ClassCastException because the last line attempts to assign an array of Object to an array of Integer. To resolve this issue, one must manually copy the elements of the Object array to a newly created Integer array.
Integer[] intArray = new Integer[a.length]; for (int i = 0; i < a.length; i++) { intArray[i] = (Integer) a[i]; }
Alternatively, one can utilize the Arrays.copyOf() or Arrays.copyOfRange() methods:
Integer[] intArray = Arrays.copyOf(a, a.length, Integer[].class); Integer[] intArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
The above is the detailed content of How Do I Safely Cast an Object Array to an Integer Array in Java?. For more information, please follow other related articles on the PHP Chinese website!