Java:必须转换为 short,不能使用 shorthand 'S'

Java: must cast to short, cannot use shorthand 'S'

我正在尝试调用一个需要短值的函数。以下作品:

i.setDamage((short) 10);

然而,这不是:

i.setDamage(10S);

根据我正在使用的IDE,这应该可行。为什么不呢?我正在使用 Maven 和 Java 7.

根据 Java Language Specification, Section 3.10.1,整数文字的唯一整数类型后缀是 L(或小写 l)。

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).

你只需要坚持演员表。 (尽管如果值在范围内,您可以只使用整数文字而不进行强制转换。)

根据 Java 语言,long 值将只包含 L 的后缀。

参考

Java Primitive Data types

JAVA 没有为 short 提供任何后缀,例如 Ss。您需要使用 (short)100.

转换为 short

可能的值为

int num = 20; //Decimal
int num = 020; //octal
int num = 0x20; //Hexadecimal
int num = 0b1010; //binary
long num = 563L; //long

在JDK7中,你可以在一个整型文字中嵌入一个或多个下划线,如

int num = 19_90;