本文介绍了任何想法为什么我需要一个整数字面量到(int)这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中

int i = -128;
Integer i2 = (Integer) i; // compiles

Integer i3 = (Integer) -128; /*** Doesn't compile ***/

Integer i4 = (Integer) (int) -128; // compiles
Integer i4 = -128; // compiles
Integer i5 = (int) -128; // compiles
Integer i6 = (Integer) (-128); // compiles
Integer i7 = (Integer) 0-128; // compiles

我不能演示 -128 (Integer)但我可以转换(int)-128

I can't cast -128 with (Integer) but I can cast (int) -128.

我一直认为 -128 int 类型并使用(int)应该是多余的。

I always thought -128 was of int type and casting it with (int) should be redundant.

i3

cannot find symbol variable Integer

我尝试使用Java 6 update 29和Java 7 update 1.

I tried this with Java 6 update 29 and Java 7 update 1.

编辑: $ c> +128 而不是 -128

You get the same behavior with +128 instead of -128. It does appear to be confusion between unary and binary operators.

推荐答案

编译器尝试减去 128 (Integer)而不是将 -128 / code>。添加()修复它

The compiler tries to subtract 128 from (Integer) instead of casting -128 to Integer. Add () to fix it

Integer i3 = (Integer) -128; // doesn't compile
Integer i3 = (Integer) (-128); // compiles

根据BoltClock的意见,转换为 int 按预期工作,因为它是一个保留字,因此不能解释为一个标识符,这对我有意义。

According to BoltClock in the comments the cast to int works as intended, because it is a reserved word and therefore can't be interpreted as an identifier, which makes sense to me.

和Bringer128找到JLS参考。

And Bringer128 found the JLS Reference 15.16.

 CastExpression:
    ( PrimitiveType Dims ) UnaryExpression
    ( ReferenceType ) UnaryExpressionNotPlusMinus

如你所见,转换为原始类型需要任何 UnaryExpression 转换为引用类型需要 UnaryExpressionNotPlusMinus 。这些是在之前的CastExpression之前定义的。

As you can see, casting to a primitive type requires any UnaryExpression, whereas casting to a reference type requires a UnaryExpressionNotPlusMinus. These are defined just before the CastExpression at JLS 15.15.

这篇关于任何想法为什么我需要一个整数字面量到(int)这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:08