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, e.g.
list.add(1.0);
list.add(1D);
See more on this question at Stackoverflow