为什么在尝试将 Double
初始化为 int
时出现错误,即使在使用基本类型 时它没有抛出异常双
?
Double a = 1; // error - incompatible types
Double b = 1.0; // OK
double c = 1; // OK
为什么类 Double
和原始类型 double
的行为不同?
最佳答案
当您将 Double
初始化为:
Double a = 1;
需要做两件事:
- 将
int
装箱到Integer
- 从
Integer
扩大到Double
尽管装箱没问题,但从 Integer
扩大到 Double
是无效的。因此,它无法编译。
请注意,Java 不支持 Widening 后跟 Boxing 转换,如 JLS §5.2: 中指定的那样
Assignment contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
您的第 2 作业通过了装箱转换。
虽然第 3 个 任务经历了扩大转换。
关于java - 为什么我不能将 Double 对象设置为等于 int? - java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22018921/