0

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?

Thuy
  • 1,493
  • 1
  • 11
  • 11

1 Answers1

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