设置短值 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2294934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting Short Value Java
提问by Mubashar
I am writing a little code in J2ME. I have a class with a method setTableId(Short tableId)
. Now when I try to write setTableId(100)
it gives compile time error. How can I set the short value without declaring another short variable?
我正在用 J2ME 编写一些代码。我有一个带有方法的类setTableId(Short tableId)
。现在,当我尝试编写setTableId(100)
它时,会出现编译时错误。如何在不声明另一个短变量的情况下设置短值?
When setting Long
value I can use setLongValue(100L)
and it works. So, what does L
mean here and what's the character for Short
value?
设置Long
值时我可以使用setLongValue(100L)
并且它有效。那么,L
这里的含义是什么,Short
价值的特征是什么?
Thanks
谢谢
采纳答案by Lauri
In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L
, D
, F
to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.
在 Java 中,整数文字默认为 int 类型。对于其他一些类型,您可以使用不区分大小写的字母作为后缀,例如L
, D
,F
以分别指定 long、double 或 float。请注意,通常的做法是使用大写字母以提高可读性。
The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:
Java 语言规范没有为字节或短类型提供相同的语法糖。相反,您可以使用显式转换来声明它:
byte foo = (byte)0;
short bar = (short)0;
In your setLongValue(100L)
method call, you don't have to necessarily include the L
suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.
在您的setLongValue(100L)
方法调用中,您不必包含L
后缀,因为在这种情况下,int 文字会自动扩展为 long。这在 Java 语言规范中称为扩展原语转换。
回答by Lawrence Dol
You can use setTableId((short)100)
. I think this was changed in Java 5 so that numeric literals assigned to byte or short and within range for the target are automatically assumed to be the target type. That latest J2ME JVMs are derived from Java 4 though.
您可以使用setTableId((short)100)
. 我认为这在 Java 5 中已更改,以便分配给 byte 或 short 并且在目标范围内的数字文字会自动假定为目标类型。不过,最新的 J2ME JVM 源自 Java 4。
回答by er4z0r
There is no such thing as a byte or short literal. You need to cast to short using (short)100
没有字节或短文字这样的东西。您需要使用(short)100
回答by matt burns
Generally you can just cast the variable to become a short
.
通常,您可以将变量强制转换为short
.
You can also get problems like this that can be confusing. This is because the +
operator promotes them to an int
您也可能会遇到此类令人困惑的问题。这是因为+
运营商将他们提升为int
Casting the elements won't help:
铸造元素无济于事:
You need to cast the expression:
您需要转换表达式: