我想知道为什么我们能这样做:
Long l = 2L;
Float f = 2f;
Double d = 2d;
Run Code Online (Sandbox Code Playgroud)
甚至
Double d = new Double(2);
Run Code Online (Sandbox Code Playgroud)
并不是
Short s = 2s; //or whatever letter it could be
Run Code Online (Sandbox Code Playgroud)
也不
Short s = new Short(2); //I know in this case 2 is an int but couldn't it be casted internally or something?
Run Code Online (Sandbox Code Playgroud)
为什么我们需要使用String或short来构造构造函数.
根据这个答案,int常量被隐式转换为short类型.
但在我的单元测试中,我想测试一个返回Short的getValue()函数.
assertEquals(obj.getValue(), 42);
Run Code Online (Sandbox Code Playgroud)
显然上面的方法不起作用,所以我尝试使用Short.valueOf
assertEquals(obj.getValue(), Short.valueOf(42));
Run Code Online (Sandbox Code Playgroud)
然而,这仍然抱怨 - 尽管上面提到了隐含的转换 - 所以我必须施展文字.
assertEquals(obj.getValue(), Short.valueOf((short)42));
Run Code Online (Sandbox Code Playgroud)
Short.valueOf((短)5)似乎有点乱!有更干净的方式吗?(新短片("42")同样可怕!)
请考虑以下代码段:
// automatic casting works for int to byte conversion as integer literal 127
// is in the range for byte
byte b1 = 127; //OK
// automatic casting doesn't work for long to int conversion
// even if long literal is in the range of int.
int i5 = 100L; // NOT OK - compilation error
Run Code Online (Sandbox Code Playgroud)
这种行为有什么解释吗?
为什么在int到byte的情况下不需要显式转换,但需要long to int?
该如何转换的Java诠释成字节?问题不同.当int值超出范围时,它是关于int到byte的隐式转换的问题.
任何人都知道为什么编译器不能在'short'中输出值'7'?显式转换正在工作,但在传递参数时它不起作用!
class Alien {
String invade(short ships) { return "a few"; }
String invade(short... ships) { return "many"; }
}
public class Wind {
public static void main(String [] args) {
short temp = 7;
System.out.println(new Alien().invade(7));
}
}
Run Code Online (Sandbox Code Playgroud)