【发布时间】:2018-06-07 06:47:49
【问题描述】:
byte b =10;
int a = b; // Primitive data type widening
// Works perfectly fine
上面的代码不会给出错误/警告。但是为什么同样不适用于下面提到的代码?
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 可以保存任何和所有字节值,为什么数组不是这种情况?
毕竟他们都持有地址。如果 ref 变量可以这样做,这将是向上转型。
【问题讨论】:
-
int[] i1 = b;- b 没有复制到i1,i1将指向b指向的相同地址。那么,如果将整数分配给i1[0](引用b并且是字节数组 - 不是 int 数组)会发生什么? -
对不起,我没有关注,您能详细说明一下吗? @BackSlash
标签: java pointers casting pass-by-reference