2

I wrote the following in my class:

public class Test{
    public static void main(String[] args){
        List<? extends Number> list = new ArrayList<Integer>();
        list.add(new Integer(5));
    }
}

But this won't compile and gives an error:

error: no suitable method found for add(Integer)
   list.add(new Integer(5));

I'm looking for a simple clarification of this problem.

guerda
  • 23,388
  • 27
  • 97
  • 146
Scorpion
  • 577
  • 4
  • 21
  • Note also you don't need to say `new Integer(5)`, the compiler will automatically box a primitive `int` into an `Integer` when needed, without wasting extra memory to create a `new Integer`. – dimo414 Jan 28 '14 at 14:23
  • @dimo414 that's only the case for integers between `-128` and `127` and it also holds true for `new Integer(5)`, i.e. two references the integer `5` will always be [the same instance](http://stackoverflow.com/questions/5117132/integer-wrapper-objects-share-the-same-instances-only-within-the-value-127). – dtech Jan 28 '14 at 14:24
  • Which `5` certainly is. Even in the general case, the compiler is able to make autoboxing optimizations which you prevent if you explicitly call `new Integer()` - there's simply no reason to make that extra call in normal code. – dimo414 Jan 28 '14 at 14:26
  • @dimo414 No, Integer and int can be (un-)boxed freely, it doesn't matter what you write. The compiler will automatically translate `list.add(5)` into `list.add(new Integer(5))` so you're not preventing any optimizations. – dtech Jan 28 '14 at 14:28
  • You are patently confused. The example you link to discusses autoboxed `int`s, and if you explicitly call `new Integer()` you *always* allocate a new object. Try it: `new Integer(5) == new Integer(5)` returns `false`. – dimo414 Jan 28 '14 at 14:30

0 Answers0