首页 > 解决方案 > 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)

标签: java

解决方案


您有一个Doubles 列表,并且您正在尝试向int其中添加一个...

这个说法

temp.add(num);

在将其添加到列表之前,首先需要num对其包装形式进行装箱,即(因为列表采用引用类型,而不是原语)。java.lang.Integer

接下来发生的事情是您尝试将 an 添加Integer到 s 的集合中Double。这是不允许的。Integer不是 的子类Double。这些是兄弟类型(它们都是 的子类Number),但DoubleInteger.

据我了解, int num 将被隐式转换为 double

当目标为double时,是的,该数字将被提升。但是,如果目标是Double,编译器会拒绝隐式执行此操作(它必须在将其设置为 a 之前将其装箱intInteger并且Double在那里失败)。

如果您想快速修复,可以使用double以下类型num

for (double num: nums) {
    temp.add(num);
}

推荐阅读