简体   繁体   中英

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. If I can assign an int to a double variable like this: double num = 1; due to automatic promotion, then why can't I add a 1 to ArrayList of Double via automatic promotion?

You're not trying to convert int to double ; you're trying to convert int to Double , which is a combination of boxing and the implicit conversion from int to double . 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 num1 = 1; // Invalid
Long num2 = 1L; // Valid

In your case, you just need to use a double literal, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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