Dónal Dónal - 4 months ago 7
Java Question

List<?> or List<Object>

I have a method whose argument should be "a List of anything". The method will not modify the contents of the List. Is it more correct to define this method as

void foo(List<?> list) {
}


or

void foo(List<Object> list) {
}


and what exactly is the difference?

Answer

Short answer, using List<?> will allow you to accept something like List<String> while using List<Object> won't.

This is discussed in the official generics trail, here and here.

[...] here is a naive attempt at writing it using generics (and the new for loop syntax):

   void printCollection(Collection<Object> c) {
       for (Object e : c) {
           System.out.println(e);
       }
   }

The problem is that this new version is much less useful than the old one. Whereas the old code could be called with any kind of collection as a parameter, the new code only takes Collection<Object>, which, as we've just demonstrated, is not a supertype of all kinds of collections!
So what is the supertype of all kinds of collections? It's written Collection<?> (pronounced "collection of unknown"), that is, a collection whose element type matches anything. It's called a wildcard type for obvious reasons. We can write:

   void printCollection(Collection<?> c) {
       for (Object e : c) {
           System.out.println(e);
       }
   }

and now, we can call it with any type of collection.