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?
Asked
Active
Viewed 148 times
0
-
1What is the type of your ArrayList? Can you show the code? – talnicolas Oct 23 '14 at 20:22
-
Why are you not adding `1.0` or using `List
`? – Peter Lawrey Oct 23 '14 at 20:49 -
`public Double makeDouble(int n) { return n + 0.0D }` – Stephen P Oct 23 '14 at 20:50
-
Sorry, I want to clarify that the ArrayList is: ArrayList
, I wonder why the diamond bracket part of my question got deleted. It seems that ArrayList – Thuy Oct 24 '14 at 21:28got truncated to ArrayList in my question.
1 Answers
7
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);

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
Thank you for explaining the reason why I can't put a 1 for example in an ArrayList
, it's because 1 can't be boxed into Double. – Thuy Oct 24 '14 at 22:08