Java 中的包装类之间可以进行类型转换吗?
这里的代码是我尝试过的:
public class Test
{
public static void main(String[] args)
{
Double d = 100.04;
Long l = (long) d.doubleValue(); //explicit type casting required
int i = (int) l; //explicit type casting required
System.out.println("Double value " + d);
System.out.println("Long value " + l);
System.out.println("Int value " + i);
}
}
为什么这个程序中的 Long
没有转换为 int
?
最佳答案
Long l = (long)d.doubleValue(); //explicit type casting required
int i = (int)l; //Not valid, because here you are casting a Wrapper Long
在上面的行中,无法将 l 强制转换为 int,因为包装类只能通过自动装箱和拆箱进行。引用:https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html 。 包装类仅转换为其相应的原始类型。
long l = (long)d.doubleValue(); //explicit type casting required
int i = (int)l; //valid, because here you are casting primitive to primitive
在上面的行中,l 可以转换为 int,因为 long 是原始类型,而 int 也是原始类型。这里将发生原始的窄化转换,因为从 long 到 int 的转换可能会导致一些精度的损失。
关于java - Java 中的包装类之间可以进行类型转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32036060/