首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Java原语到包装类的转换

从Java原语到包装类的转换
EN

Stack Overflow用户
提问于 2015-02-05 03:43:20
回答 2查看 1.8K关注 0票数 5

当将原语分配给包装类引用时,我对Java编译器的行为感到困惑。请看下面的代码。带注释的行不编译。

我不明白为什么:

  1. 可以将byte分配给ByteShort,但不能分配IntegerLong引用。
  2. 可以将short分配给ByteShort,但不能分配IntegerLong引用。
  3. 可以将int分配给ByteShortInteger,但不能分配Long引用。
  4. long可以分配给Long,但不能分配给ByteShortInteger引用。

我看不出图案。任何对此的洞察力都会很有帮助。谢谢。

代码语言:javascript
复制
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;
EN

回答 2

Stack Overflow用户

发布于 2015-02-06 05:34:05

这似乎是编译器特有的行为。当我将您的代码粘贴到运行Java 7的Eclipse中时,我没有看到您为shortInteger报告编译器错误或向Integer报告byte的编译器错误。

相反,我看到byteshortint都可以分配给ByteShortInteger,但不能分配Longlong只能分配给Long。有趣的是,如果您将变量更改为原语而不是包装器类型,那么byteshortint的行为不会改变,但是现在从其他类型到long的分配也能工作。

代码语言:javascript
复制
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 ),而不是因为它是语言的一个有文档的部分。

票数 1
EN

Stack Overflow用户

发布于 2015-02-06 03:55:31

从我的研究中,我发现字节是一个8位有符号整数.空头是16位有符号整数。因此,我可以理解为什么它们是相容的,它们都是两个补码的有符号整数,强调的是符号。long是64位的整数,但也可以是无符号的(考虑到它有比较无符号长的方法)。这可能解释了为什么转换到long会导致错误--您将一个有符号的字节转换为一个可能没有符号的long。(来源:在http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html阅读原语)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28335839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档