0

Are they exactly the same or used for different situations?

public List<? extends Object> do(){
   return ...
}

VS

public List<Object> do(){
  return...
}
user697911
  • 8,475
  • 15
  • 71
  • 139
  • The former may return a list of some subclass of Object. The latter returns a list of objects of arbitrary classes. See also ["List extends MyType>"](https://stackoverflow.com/questions/918026/list-extends-mytype). – Andy Thomas Jun 08 '17 at 21:18
  • Generics is tough. The PECS question should point you in the right direction. – fps Jun 08 '17 at 23:55

1 Answers1

1

Those are not the same.

A List<? extends Object> may be a list of any type.

Since you don't know what type the list actually contains, you can't put anything into it.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • Since everything is implicitly a subclass of Object, why aren't they the same? I mean in both cases, the do() can return a list of "everything". Isn't right? – user697911 Jun 08 '17 at 21:20
  • @user697911 Try both with `do().add(new Object())`. – Radiodef Jun 08 '17 at 21:21
  • No. `List extends Object>` means you _don't know_ what type the list is supposed to have; just that whatever type it is extends `Object`. It might actually be a `List`, so you can't put in a `Dog`. – SLaks Jun 08 '17 at 21:21
  • The wildcard `extends` syntax says that the list contains references all of the same type, which type is a subtype of the upper bound, `Object`. Without the wildcard, `List`, it's a list of references all of the named generic element type, `Object`, but each element can be of a different subtype of the named type. – Lew Bloch Jun 08 '17 at 23:47