为什么会投INT []反对意见,但不反对[]? [英] Why can you cast int[] to Object, but not to Object[]?

查看:114
本文介绍了为什么会投INT []反对意见,但不反对[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这个作品:

  INT I;
对象=(对象)我;
INT []吨;
对象B =(对象)吨;
的String [] S;
[对象] T =(对象[])S;

但是,这并不:

  INT []吨;
[对象] Z =(对象[])吨;

所有的一切我得到的第一部分(拳击),但我觉得它非常直观第二部分不起作用。是否有一个具体原因(旁边字符串从Object继承和Int不能从Object继承)?

编辑:

要改进我的问题,这也可以工作:

  int类型的= 2;
INT B = 3;
INT C = 4;
INT D = 2;
[对象] 0 =新的对象[] {A,B,C,D};

但随后下列不:

  INT [] T =(INT [])O;

令人惊讶你的字符串得到同样的问题:

 字符串SA =A;
串SB =B;
字符串SC =C;
串SD =D;
[对象]所以=新对象[] {SA,SB,SC,SD};
的String [] ST =(字符串[])左右;

收益率的最后一行类转换异常。还是这个作品:

 对象[] = SY(对象[])新的String [] {SA,SB,SC,SD};
的String [] = SZ(字符串[])SY;


解决方案

我刚刚发现我一直在寻找自己的答案。你之所以不能施放 INT [] 对象[] 不是因为int是一种原始的,不延长对象,但因为 INT [] 本身并没有延长对象[] 。在code:

  INT [] T = INT新[0];
对象OT = T;
的System.out.println(OT的instanceof对象[]);
// - >版画假
的String [] S =新的String [0];
对象OS =秒;
的System.out.println(OS INSTANCEOF对象[]);
// - >版画真

编辑:拳击是必要的,因为Eclipse的人都知道 INT [] 对象[] 是不兼容的

编辑二:顺便说一下这个如果(OBJ的instanceof对象[])允许请检查是否盒装阵列是一种原始类型的数组

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;

解决方案

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.

这篇关于为什么会投INT []反对意见,但不反对[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆