从Java原语转换为包装类 [英] Converting from Java primitive to wrapper classes
问题描述
在将基元分配给包装类引用时,我对Java编译器的行为感到困惑。请参阅下面的代码。带注释的行不会编译。
I am mystified by the behavior of the Java compiler when assigning primitives to wrapper class references. Please see the code below. The lines with comments don't compile.
我不明白原因的逻辑:
- 一个
字节
可以分配给字节
或短
,但不是整数
或长
参考 - a
短
可以分配到字节
或短
,但是不是整数
或长
参考 - 一个
int
可以分配到字节
,短
或整数
,但不是长
参考 - a
long
可以分配到长
,但不能字节
,短
或整数
参考
- a
byte
can be assigned to aByte
orShort
, but notInteger
orLong
reference - a
short
can be assigned to aByte
orShort
, but notInteger
orLong
reference - an
int
can be assigned to aByte
,Short
, orInteger
, but notLong
reference - a
long
can be assigned to aLong
, but notByte
,Short
orInteger
reference
我看不到模式。对此的任何见解都将非常有用。
谢谢。
I cannot see the pattern. Any insight into this will be really helpful. Thanks.
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;
推荐答案
让我们看一下<允许的转换类型a href =http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2\"rel =nofollow>分配上下文。
主要:
分配上下文允许使用一个以下内容:
-
身份转换
an identity conversion
扩大原始转换
扩大参考转化
一个拳击转换,可选择后跟扩展引用转换
a boxing conversion optionally followed by a widening reference conversion
取消装箱转换,可选择后跟扩展原始转换。
an unboxing conversion optionally followed by a widening primitive conversion.
(注意我强调一个。)
大多数您编译的示例,例如
Most of your examples that do not compile, for example
Integer s11 = (short)7;
要求扩展原始转换,然后进行装箱转换。这不是允许的转换。
require a widening primitive conversion followed by a boxing conversion. This is not a permitted conversion.
但是你可能想知道为什么下面的例子会编译:
But then you might wonder why the following example does compile:
Byte s9 = (short)7;
这是缩小的原始转换,然后是装箱转换。
这是一个特例:
此外,如果表达式是常量表达式
byte
,short
,char
或int
[...]如果变量的类型为:
In addition, if the expression is a constant expression of type
byte
,short
,char
, orint
[...] a narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
-
字节
,常量表达式的值可在字节$ c类型中表示$ c>。
Byte
and the value of the constant expression is representable in the typebyte
.
短
,常量表达式的值可在<$类型中表示c $ c>短。
Short
and the value of the constant expression is representable in the type short
.
字符
及其值常量表达式可在 char
类型中表示。
Character
and the value of the constant expression is representable in the type char
.
这种特殊情况是必要的,因为无法表达整数li比 int
更窄的类型的teral。
This special case is necessary because there is no way to express an integer literal of a type narrower than int
.
这篇关于从Java原语转换为包装类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!