use*_*726 5 java boxing type-conversion
在将基元分配给包装类引用时,我对Java编译器的行为感到困惑.请参阅下面的代码.带注释的行不会编译.
我不明白为什么的逻辑:
byte可以分配给a Byte或Short但不分配Integer或Long引用short可以分配给a Byte或Short但不分配Integer或Long引用int可以被分配给一个Byte,Short或者Integer,但不Long引用long可以被分配到一个Long,但不是Byte,Short或Integer参考我看不出这种模式.任何洞察力都会非常有用.谢谢.
Byte s5 = (byte)7;
Short s6 = (byte)7;
Integer s7 = (byte)7; // Does not compile
Long s8 = (byte)7; // Does not compile
Byte s9 = (short)7;
Short s10 = (short)7;
Integer s11 = (short)7; // Does not compile
Long s12 = (short)7; // Does not compile
Byte s1 = (int)7;
Short s2 = (int)7;
Integer s3 = (int)7;
Long s4 = (int)7; // Does not compile
Byte s13 = (long)7; // Does not compile
Short s14 = (long)7; // Does not compile
Integer s15 = (long)7; // Does not compile
Long s16 = (long)7;
Run Code Online (Sandbox Code Playgroud)
根据我的研究,我发现一个字节是一个 8 位有符号整数。Shorts 是 16 位有符号整数。因此我可以明白为什么它们是兼容的,它们都是二进制补码有符号整数,强调有符号。long 是一个 64 位整数,但它也可以是无符号的(考虑到它具有比较无符号 long 的方法)。这可能可以解释为什么您的 long 转换会导致错误 - 您会将有符号字节转换为潜在的无符号 long 。(来源:在http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html上阅读有关原语的内容)