Ross Ross - 1 year ago 88
Java Question

casting Object array to Integer array error

What's wrong with the following code?

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

The code has the following error at the last line :
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

Answer Source

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

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

Here the reason to hitting an ClassCastException is you can't treat a list of Integer IS-A list of Object although an Integer IS-A(n) Object.

And the following also will not give an ClassCastException.

Object[] a = new Integer[1];
Integer b=1;
Integer[] c = (Integer[]) a;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download