Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中执行类型转换时出现编译器错误_Java_Casting - Fatal编程技术网

在Java中执行类型转换时出现编译器错误

在Java中执行类型转换时出现编译器错误,java,casting,Java,Casting,让我们看看Java中的以下表达式 int temp = -254; Integer temp2 = (Integer) temp; // compiles because of autoboxing Integer temp3 = (Integer) -254; // doesn't compile - illegal start of type. Integer temp4 = (Integer) 10-254; // compiles Integer t

让我们看看Java中的以下表达式

int temp = -254;
Integer temp2 = (Integer) temp;        // compiles because of autoboxing

Integer temp3 = (Integer) -254;       // doesn't compile - illegal start of type.
Integer temp4 = (Integer) 10-254;     // compiles

Integer temp5 = (Integer) (int) -254; // compiles
Integer temp6 = -254;                 // compiles
Integer temp7 = (int) -254;           // compiles

在上面的表达式中,为什么这些表达式
(Integer)10-254
(int)-254
有效,而表达式
(Integer)-254
即使常量
-254
可以完美地计算为
Integer

这是一个有趣的边缘情况,编译器尝试对
integer
类和
int
文本执行整数减法(254)

请注意,以下内容编译后更为明确:

    Integer temp3 = (Integer)(-254)

更具体地说,这符合:

强制转换表达式在运行时转换一个数值类型的值 另一数值类型的类似值;或者在编译时确认 一个表达式的类型是布尔型的;或者在运行时检查 引用值引用类为的对象的时间 与指定的引用类型兼容

CastExpression:
(原语类型Dimsopt)一元表达式
(ReferenceType)一元表达式NotPlusMinus