Home  >  Article  >  Java  >  How Do I Safely Cast an Object Array to an Integer Array in Java?

How Do I Safely Cast an Object Array to an Integer Array in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 21:50:02375browse

How Do I Safely Cast an Object Array to an Integer Array in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn