0

I am new to generics, so bear with me.

I was sure I understood what this statement meant:

 List<? extends Number> nums = new ArrayList<>();

To me, it means List will accept any objects added to the list which are of the Number class or extend the Number class.

So when I added a double to the list, I expected it to work

List<? extends Number> nums = new ArrayList<>();
nums.add(3.14);

However, I get the error List cannot be applied to double

the_prole
  • 8,275
  • 16
  • 78
  • 163
  • You cant add anything to a Collection which has `? extends T` – TheLostMind Feb 18 '16 at 05:35
  • But I thought that is how upper bounded wild cards worked. – the_prole Feb 18 '16 at 05:35
  • You need to use `? super Double`. Go through the post I used to close your question as dupe – TheLostMind Feb 18 '16 at 05:36
  • But Double extends Number. – the_prole Feb 18 '16 at 05:38
  • `? extends T` acts as a *Producer* so you cant add anything to it – TheLostMind Feb 18 '16 at 05:39
  • This is mind boggling. – the_prole Feb 18 '16 at 05:51
  • Indeed it is.. So you got the answer to your question? – TheLostMind Feb 18 '16 at 05:52
  • 1
    Yes. Thanks Lost Mind. – the_prole Feb 18 '16 at 06:04
  • @the_prole it's not so mind boggling when you think of it the right way. `List extends Number> nums = new ArrayList()` is valid, but you can't do `nums.add(3.14)` for an `ArrayList`. It looks like what you want is a `List`. Not a `List extends Number>`. – Louis Wasserman Feb 18 '16 at 06:04
  • @LouisWasserman I was trying to understand parameterized types in the context of creating generic methods e.g. from the [java doc](https://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html). I'm confused because I can have a parameterized paramter ArrayList extends Number> and can accept any kind of integer, double, etc. But I cannot declared a paramterized ArrayList in the same way, and add double and integers to it... understand why I'm confused? I don't know if I make any sense. I apologize for that. – the_prole Feb 18 '16 at 06:14
  • @the_prole You can't add doubles or integers to it because you don't know _which one_ it takes, doubles or integers or something else. If you know you can add _any_ `Number`, whether it's a double or an integer, then you should have a `List`. – Louis Wasserman Feb 18 '16 at 06:15
  • @LouisWasserman Okay, I get it now. Whoa. – the_prole Feb 18 '16 at 06:20

0 Answers0