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
  • 3,026
  • 7
  • 31
  • 39
Omkar Shetkar
  • 3,488
  • 5
  • 35
  • 50

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
  • 868,454
  • 176
  • 1,908
  • 1,964