当将原语分配给包装类引用时,我对Java编译器的行为感到困惑。请看下面的代码。带注释的行不编译。
我不明白为什么:
byte分配给Byte或Short,但不能分配Integer或Long引用。short分配给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;发布于 2015-02-06 05:34:05
这似乎是编译器特有的行为。当我将您的代码粘贴到运行Java 7的Eclipse中时,我没有看到您为short向Integer报告编译器错误或向Integer报告byte的编译器错误。
相反,我看到byte、short和int都可以分配给Byte、Short和Integer,但不能分配Long,long只能分配给Long。有趣的是,如果您将变量更改为原语而不是包装器类型,那么byte、short和int的行为不会改变,但是现在从其他类型到long的分配也能工作。
javac 1.7.0_02
| byte | Byte || short | Short || int | Integer || long | Long |
From byte | Yes | Yes || Yes | Yes || Yes | No || Yes | No |
From short | Yes | Yes || Yes | Yes || Yes | No || Yes | No |
From int | Yes | Yes || Yes | Yes || Yes | Yes || Yes | No |
From long | No | No || No | No || No | No || Yes | Yes |
Eclipse Indigo
| byte | Byte || short | Short || int | Integer || long | Long |
From byte | Yes | Yes || Yes | Yes || Yes | Yes || Yes | No |
From short | Yes | Yes || Yes | Yes || Yes | Yes || Yes | No |
From int | Yes | Yes || Yes | Yes || Yes | Yes || Yes | No |
From long | No | No || No | No || No | No || Yes | Yes |考虑到不同的编译器允许不同的转换,我怀疑JLS中并没有具体说明“正确”的行为。似乎某些转换是在幕后完成的,因为编译器编写人员认为它很方便(例如,允许使用byte a = (int)1,但不允许使用byte a = (int)1000 ),而不是因为它是语言的一个有文档的部分。
发布于 2015-02-06 03:55:31
从我的研究中,我发现字节是一个8位有符号整数.空头是16位有符号整数。因此,我可以理解为什么它们是相容的,它们都是两个补码的有符号整数,强调的是符号。long是64位的整数,但也可以是无符号的(考虑到它有比较无符号长的方法)。这可能解释了为什么转换到long会导致错误--您将一个有符号的字节转换为一个可能没有符号的long。(来源:在http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html阅读原语)
https://stackoverflow.com/questions/28335839
复制相似问题