为什么数组分配不兼容,即使它们的数据类型是兼容的? [英] Why are array assignments incompatible, even though their data types are?

查看:92
本文介绍了为什么数组分配不兼容,即使它们的数据类型是兼容的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

byte b =10;   
int a = b;   // Primitive data type widening
             // Works perfectly fine

上面的代码不会给出任何错误/警告.但是为什么相同的方法不适用于以下提到的代码?

the above code will give no error/warnings. But why is the same not applicable for the below mentioned code?

byte[] b = new byte[10];
int[] i1 = b;             //Cannot convert from byte[] to int[]
int[] i2 = new byte[10];  //Cannot convert from byte[] to int[]

我的问题是,由于int可以容纳所有字节值,为什么数组不是这种情况?

my question is, since int can hold any and all byte values, why is this not the case with arrays?

他们俩毕竟都持有住址.如果引用变量有可能,这将是上演.

they are both holding the addresses afterall. And this would be upcasting if this was possible for ref variables.

推荐答案

语言规范在

以下规则定义了数组之间的直接超类型关系 类型:

The following rules define the direct supertype relation among array types:

  • 如果ST都是引用类型,则S[] >1 T[] iff S >1 T.

  • If S and T are both reference types, then S[] >1 T[] iff S >1 T.

Object >1 Object[]

Cloneable >1 Object[]

java.io.Serializable >1 Object[]

如果P是原始类型,则:

  • Object >1 P[]

Cloneable >1 P[]

java.io.Serializable >1 P[]

最后的项目符号(如果P是原始类型...")表明该语言未定义不同原始类型的数组之间的任何关系.唯一有效的分配是:

The final bullets ("If P is a primitive type...") show that the language does not define any relationship between arrays of differing primitive types. The only valid assignments are:

byte[] bs = new byte[10];

byte[] bs2 = bs;
Object obj = bs;
Cloneable cl = bs;
Serializable ser = bs;

这没有提供关于为什么这样的答案;您必须要询问语言设计师.但是,像 Eran 所示的简单示例说明了为什么按照OP的建议这样做并不安全.

This doesn't provide an answer as to why it is like this; you'd have to ask the language designers. However, simple examples like that shown by Eran demonstrate why it would not be safe to do as OP proposes.

应该注意的是,第一行-允许类似

It should be noted that the first line - which permits an assignment like

Object[] obj = new String[10];
obj[0] = new Object();  // ArrayStoreException!

是一个设计错误:数组是协变的,因此它们不是类型安全的.这是强烈建议使用泛型而不是数组的原因之一,因为泛型是不变的,因此可以防止此类分配.

was a design error: that arrays are covariant makes them not type safe. This is one reason to strongly prefer generics to arrays, since generics are invariant, and so prevent such assignments.

这篇关于为什么数组分配不兼容,即使它们的数据类型是兼容的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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