I am studying Wildcards from Oracle’s documentation, and I can’t understand the following section:
*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!
*
https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
The tutorial says Collection<Object>
is not a supertype of all kinds of collections. I am curious what are some examples of code that are not a subtype of Collection<Object>
?
From my understanding, all classes are descendants of the Object class. Interfaces and primitive types may be an exception.
Jinny is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.