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?
means you can assign any type of List to it and List<Object> means you can store any type of object into it. That's the real difference between List<?> and List<Object> in Java.
In practical terms there is no difference, they both compile down to the exact same code. List<Object> though is showing that you have thought about what will go in the list and know it could be anything, whereas List on its own shows nothing.
In category theory, an abstract branch of mathematics, and in its applications to logic and theoretical computer science, a list object is an abstract definition of a list, that is, a finite ordered sequence.
Lists are objects too. An important method for lists is append(item).
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 writtenCollection<?>
(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.
The List<Object>
has parameterized type Object
which essentially means that you can add all objects in the list.
However, List<?>
means that is a list of unknowns. As long as you're not going to add anything to the list, it's essentially the same as List<Object>
but you will have to worry with circumstances as follows:
List<?> unknownList = new ArrayList<String>();
unknownList.add(new Object()); //Compilation error.
The ?
(in this case) means that you can only add values of String
or is subtype of String
.
If you're just going to iterate through the list and retrieve values, List<?>
and List<Object>
is essentially the same.
More info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With