Home > Java > javaTutorial > 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
Release: 2024-10-26 21:50:02
Original
501 people have browsed it

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;
Copy after login

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];
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template