Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you cast int[] to Object, but not to Object[]?

So this works:

int i;
Object a  = (Object) i;
int[] t;
Object b = (Object) t;
String[] s;
Object[] t = (Object[]) s;

But this does not:

int[] t;
Object[] z = (Object[]) t;

All in all I get the first part (boxing), but I find it highly unintuitive that the second part does not work. Is there a specific reason why (beside String inheriting from Object and int not inheriting from Object)?

Edit:

To refine my question, this also works:

int a = 2;
int b = 3;
int c = 4;
int d = 2;
Object[] o = new Object[] {a,b,c,d};

But then the following does not:

int[] t = (int[]) o;

Surprisingly you get the same problem with String:

String sa = "a";
String sb = "b";
String sc = "c";
String sd = "d";
Object[] so = new Object[] {sa,sb,sc,sd};
String[] st = (String[]) so;

Yields a class cast exception on the last line. Still this works:

Object[] sy = (Object[])new String[]{sa,sb,sc,sd};
String[] sz = (String[]) sy;
like image 934
Lucas Hoepner Avatar asked Nov 23 '25 07:11

Lucas Hoepner


1 Answers

A int[] is an array of primitives but also an Object itself. It is not an array of Objects

There is no auto-boxing support for arrays. You need to pick the right type of array to start with and not be converting it at runtime.

like image 76
Peter Lawrey Avatar answered Nov 24 '25 21:11

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!