简体   繁体   English

为什么在列表中添加int时没有促销<Double>

[英]Why no promotion when adding ints to List<Double>

in Java I created an ArrayList of Double and I invoked the method list.add(1), however, I get an error. 在Java中,我创建了一个Double的ArrayList,并调用了方法list.add(1),但是,出现错误。 If I can assign an int to a double variable like this: double num = 1; 如果我可以将int分配给double变量,例如:double num = 1; due to automatic promotion, then why can't I add a 1 to ArrayList of Double via automatic promotion? 由于自动升级,为什么我不能通过自动升级为Double的ArrayList添加1?

You're not trying to convert int to double ; 您不是要将int转换为double you're trying to convert int to Double , which is a combination of boxing and the implicit conversion from int to double . 您正在尝试将int转换为Double ,这是装箱intdouble的隐式转换的组合。 That doesn't work, even in a simple assignment: 即使在简单的任务中,这也不起作用:

// Error: incompatible types: int cannot be converted to Double
Double num = 1;

It doesn't even work for Long - you need to specify a long literal: 甚至对于Long也不起作用-您需要指定一个long文字:

Long num1 = 1; // Invalid
Long num2 = 1L; // Valid

In your case, you just need to use a double literal, eg 在您的情况下,您只需要使用double精度字面量,例如

list.add(1.0);
list.add(1D); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM