【问题标题】:Java instantiate Short object in JavaJava在Java中实例化Short对象
【发布时间】:2012-07-16 14:33:31
【问题描述】:

我想知道为什么我们可以这样做:

Long l = 2L;
Float f = 2f;
Double d = 2d;

甚至

Double d = new Double(2);

而不是

Short s = 2s; //or whatever letter it could be

也没有

Short s = new Short(2); //I know in this case 2 is an int but couldn't it be casted internally or something?

为什么我们需要使用 String 或 short 的构造函数。

【问题讨论】:

  • Java 中没有短或字节字面量。
  • @Eng.Fouad 是正确的。 0xFF 在 java 中是一个 int,>> 和

标签: java short


【解决方案1】:

但你可以这样做:

Short s = 2;

或者这个:

Short s = new Short((short)2);

或者这个:

Short s = new Short("2");

只要数字在 [-2^15, 2^15-1] 范围内,上述任何一项都可以工作

【讨论】:

  • 其实不能做 Short s = new Short((short) 2);无论是那个还是我的日食都是错误的。您需要使用 short short = 2;而不是在构造函数上使用它。
【解决方案2】:

Java 的主要规则之一是任何数学运算的结果都将存储在一个大变量中以避免截断。例如,如果您将 int 与 long 相加,则结果将很长。因此,对 byte、char 或 short 的任何操作都会产生 int,即使您将 1 添加到一个字节。有两种方法可以将结果存储在相同的数据类型中:

a) 你做了显式转换:

short s=10;  
s=(short)(s+1);  

b) 你可以使用速记操作的自动增量来要求 JVM 进行隐式转换:

short s=10;  
s+=21;  

short s=10;  
s++;  

如果您需要短文字或字节文字,则必须强制转换它们,因为short 没有像Ss 这样的后缀:

byte foo = (byte)100000;
short bar = (short)100000;

【讨论】:

  • 即使添加两个shorts 或bytes 或chars 也会产生int。虽然添加两个ints 不会导致longint 在这里很特别。这是DataOutput#writeShort 采用 int 参数而不是 short 的另一个原因。
猜你喜欢
  • 2013-03-29
  • 2011-06-05
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
相关资源
最近更新 更多