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

后端 未结 6 1365
长情又很酷
长情又很酷 2020-12-21 09:52

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:

6条回答
  •  春和景丽
    2020-12-21 09:54

    As you say: String inheriting from Object and int not inheriting from Object, that's the reason. int, boolean, double... are primitive types and they don't extend from Object. You should use Integer instead of int.

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

提交回复
热议问题