0

In the following code snippet it gives compilation error on line 2 but it doesn't on line 3.

List<? extends Object> list1 = new ArrayList<>(); // line 1
list1.add("123"); // line 2

List<? extends Object> list2 = Arrays.asList("123", new Integer(12)); // line 3

If language designers have decided, not to allow to add elements into collection of element type <? extends T> then it should apply to line 3 too.

What could be the reason for this difference?

Please clarify.

nkr
  • 2,987
  • 7
  • 30
  • 39
Omkar Shetkar
  • 3,256
  • 5
  • 30
  • 44
  • 1
    You are not adding to list2 once it is initialized – user7 Jun 28 '18 at 18:39
  • 1
    Related: [What is PECS (Producer `extends`, Consumer `super`)](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). – Turing85 Jun 28 '18 at 18:44
  • Change code to `List list1 = new ArrayList<>();`, then add whatever you like. – Andreas Jun 28 '18 at 18:58

1 Answers1

6

You're calling add(?) on a List<?>.

Since the compiler doesn't know what the ? is, there is no possible value (except null) that you can pass that is guaranteed to be legal for every possible ?.

Your second example doesn't call any method that takes a ? as a parameter, so it isn't unsafe.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933