Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting Object array to Integer array error

Tags:

java

casting

What's wrong with the following code?

Object[] a = new Object[1]; Integer b=1; a[0]=b; 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;

like image 466
Ross Avatar asked Jul 12 '09 03:07

Ross


People also ask

Can we assign Integer array to Object array in C#?

It only works for arrays of reference types. Arrays of value types are a physically different size, so this cannot work.

Can we cast Object to Integer in Java?

You can't. An int is not an Object .


1 Answers

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 an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

And the following also will not give an ClassCastException.

Object[] a = new Integer[1]; Integer b=1; a[0]=b; Integer[] c = (Integer[]) a; 
like image 199
namalfernandolk Avatar answered Oct 12 '22 14:10

namalfernandolk