0

For example, is there any difference between these two method signatures?

Something<?> doIt(Collection<?> collection)

and

Something<Object> doIt(Colllection<Object> collection)
Antonio Dragos
  • 1,973
  • 2
  • 29
  • 52

1 Answers1

1

Yes, there is. This works with ? but not with Object:

List<Foo> fooList = new List<>()
doIt(fooList)

The reason is that a List<Foo> is not a List<Object> even if Foo is an Object. Why? Imagine we had a class Bar unrelated to Foo and we wrote doIt like this:

void doIt(Collection<Object> collection) {
    collection.add(new Bar())
}

Now if we were allowed to call doIt(fooList), we'd end up with a List<Foo> that contains a Bar!

Thomas
  • 174,939
  • 50
  • 355
  • 478