- From Oracle
Collection<?>
(pronounced "collection of unknown"), that is, a
collection whose element type matches anything. It's called a wildcard
type for obvious reasons.
- A variable of type
Collection<?>
is a collection that may contain any type. Your code has no idea what type of of object will be put in that collection. This is subtly different than a Collection<Object>
, which is a collection that contains objects of the Object class (it specifies Object, instead of saying that it can except anything). (Which is the parent of every object in java, including String).
You usually don't want to initialize a Collection<?>
as you can't add anything to it (as far as I am aware).
However, when you're making a function that can operate on a collection of ANYTHING, that is very useful.
For example, from you could make a function like that example from oracle.
void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
This method will be able to accept a collection of any type.
Where
void printCollection(Collection<Object> c) {
for (Object e : c) {
System.out.println(e);
}
}
Is only able to operate on a Collection<Object>
, (which is NOT a Collection<String>
, even though String is a subclass of Object)