从Java原语转换为包装类

use*_*726 5 java boxing type-conversion

在将基元分配给包装类引用时,我对Java编译器的行为感到困惑.请参阅下面的代码.带注释的行不会编译.

我不明白为什么的逻辑:

  1. a byte可以分配给a ByteShort但不分配IntegerLong引用
  2. a short可以分配给a ByteShort但不分配IntegerLong引用
  3. 一个int可以被分配给一个Byte,Short或者Integer,但不Long引用
  4. 一个long可以被分配到一个Long,但不是Byte,ShortInteger参考

我看不出这种模式.任何洞察力都会非常有用.谢谢.

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)

Sir*_*dat 0

根据我的研究,我发现一个字节是一个 8 位有符号整数。Shorts 是 16 位有符号整数。因此我可以明白为什么它们是兼容的,它们都是二进制补码有符号整数,强调有符号。long 是一个 64 位整数,但它也可以是无符号的(考虑到它具有比较无符号 long 的方法)。这可能可以解释为什么您的 long 转换会导致错误 - 您会将有符号字节转换为潜在的无符号 long 。(来源:在http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html上阅读有关原语的内容)

  • 无符号没有问题。Java 没有无符号类型,只有一些实用方法可以像无符号一样进行算术和比较。 (3认同)