为什么将Integer转换为double时不计算函数会出错?

问题描述 投票:0回答:1

为什么下面的代码工作正常,并且没有抱怨Function的返回类型是Integer而不是Double?

    public static void main(String[] args) {
          double principle = 100;         
          int interestrate = 5;         
          double amount = compute(principle, x->x*interestrate);
    }
    public static double compute(double base, Function<Integer, Integer > func){ 
        return func.apply((int)base); 
    }
java function integer double
1个回答
0
投票

之所以发生,是因为Java在不导致准确性下降的情况下自动转换类型。它可以将int转换为double,但不能将double转换为int,因为小数部分将丢失(但是您当然可以手动执行)。您可以在这里https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

中阅读
© www.soinside.com 2019 - 2024. All rights reserved.