java - Java int 不能转换为 Double
问题描述
为什么铸造会导致错误?据我了解,int num
将隐式转换为double
,但现在为避免此错误,我需要这样做temp.add((double) num);
public void test(int[] nums) {
List<Double> temp = new ArrayList<>();
for (int num: nums) {
temp.add(num);
}
}
错误:
Playground Debug
Line 6: error: no suitable method found for add(int)
temp.add(num);
^
method Collection.add(Double) is not applicable
(argument mismatch; int cannot be converted to Double)
method List.add(Double) is not applicable
(argument mismatch; int cannot be converted to Double)
解决方案
您有一个Double
s 列表,并且您正在尝试向int
其中添加一个...
这个说法
temp.add(num);
在将其添加到列表之前,首先需要num
对其包装形式进行装箱,即(因为列表采用引用类型,而不是原语)。java.lang.Integer
接下来发生的事情是您尝试将 an 添加Integer
到 s 的集合中Double
。这是不允许的。Integer
不是 的子类Double
。这些是兄弟类型(它们都是 的子类Number
),但Double
与Integer
.
据我了解, int num 将被隐式转换为 double
当目标为double
时,是的,该数字将被提升。但是,如果目标是Double
,编译器会拒绝隐式执行此操作(它必须在将其设置为 a 之前将其装箱int
,Integer
并且Double
在那里失败)。
如果您想快速修复,可以使用double
以下类型num
:
for (double num: nums) {
temp.add(num);
}
推荐阅读
- python - 如何在python的类中更改部分函数?
- c# - ValueType 上的“InstanceMethod()”和“StaticMethod(ref Type self)”之间的区别?
- javascript - 从 MYSQL 文件中删除注释
- mysql - MySQL 单一查询来确定测试/答案的匹配记录和百分比
- python - 以下python代码没有输出
- python - 试图将数组列表转换为数组
- java - Log4j 没有记录任何东西(Gradle/Eclipse)
- c# - 如何在 net.core 3.0 的 Startup.cs 中从单例中的异步方法添加数据?
- python-3.x - Bokeh TapTool 不适用于区域字形
- prolog - 如何在另一个谓词序言中一个接一个地传递列表的值