Java 在 Java 中实例化 Short 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11526432/
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
Java instantiate Short object in Java
提问by Nuno Gon?alves
I was wondering why we can do:
我想知道为什么我们可以这样做:
Long l = 2L;
Float f = 2f;
Double d = 2d;
or even
甚至
Double d = new Double(2);
and not
并不是
Short s = 2s; //or whatever letter it could be
nor
也不
Short s = new Short(2); //I know in this case 2 is an int but couldn't it be casted internally or something?
Why do we need to take the constructors either with a String or a short.
为什么我们需要使用 String 或 short 来获取构造函数。
回答by óscar López
But you cando this:
但是你可以这样做:
Short s = 2;
Or this:
或这个:
Short s = new Short((short)2);
Or this:
或这个:
Short s = new Short("2");
Any of the above will work as long as the number is in the range [-2^15, 2^15-1]
只要数字在 [-2^15, 2^15-1] 范围内,上述任何一项都将起作用
回答by Lion
One of the main rules in Java is that any mathematical operation's result will be stored in a large size variable to avoid truncation. For example if you are adding int with long the result will be long. Hence, any operation on byte, char, or short will result an int even if you added 1 to a byte.There are 2 ways to store the result in the same data type:
Java 中的主要规则之一是任何数学运算的结果都将存储在一个大大小的变量中以避免截断。例如,如果您将 int 与 long 相加,结果将会很长。因此,任何对 byte、char 或 short 的操作都会导致 int,即使您将 1 添加到 byte。有两种方法可以将结果存储在相同的数据类型中:
a) you do explicit casting:
a)您进行显式转换:
short s=10;
s=(short)(s+1);
b) You can use the auto increment of short hand operations to ask the JVM to do implicit casting:
b) 您可以使用速记操作的自动增量来要求 JVM 进行隐式转换:
short s=10;
s+=21;
OR
或者
short s=10;
s++;
if you need short or byte literal, they must be casted as there is no suffix like S
or s
for short
:
如果您需要短字面量或字节字面量,则必须将它们强制转换,因为没有像S
或s
for这样的后缀short
:
byte foo = (byte)100000;
short bar = (short)100000;