Im currently trying to study java generics and I
m trying to understand wilcards .
I was reading java docs and I encountered this information below. Can you please clarify why
Collection is not the supertype of all collections and it is when we use Collection<?> ?
Is this because , in example , we can pass a collection into a collection ?
thank you . The text from docs is below :
Consider the problem of writing a routine that prints out all the elements in a collection. Here's how you might write it in an older version of the language (that is, a pre-5.0 release):
void printCollection(Collection c) {
Iterator i = c.iterator();
for (k = 0; k < c.size(); k++) {
System.out.println(i.next());
}
} And 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, 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);
}
}