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

后端 未结 6 1371
长情又很酷
长情又很酷 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:58

    I just found the answer I was looking for myself. The reason why you cannot cast int[] to Object[] is not because int is a primitive and does not extend Object, but because int[] itself does not extend Object[]. In code:

    int[] t = new int[0];
    Object ot = t;
    System.out.println(ot instanceof Object[]);
    // --> prints 'false'
    String[] s = new String[0];
    Object os = s;
    System.out.println(os instanceof Object[]);
    // --> prints 'true'
    

    Edit: the boxing is necessary because Eclipse knows that int[] and Object[] are incompatible.

    Edit II: Btw this if(obj instanceof Object[]) allows to check wether a boxed array is an array of a primitive type.

提交回复
热议问题