0

Im currently trying to study java generics and Im 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);
    }
  }
  • `Collection` says it is a collection of Objects, a `Collection` is a collection of Integers, which are also Objects. You can add `String` to `Collection` but not to `Collection` Hence, if you want to refer to the fact the Integer are Objects you can say, I have a `Collection extends Object>` That way you know `?` is more specific than `Object` but you only need to know they're Objects. eg. You cannot add a String to it. – matt Aug 04 '22 at 13:35
  • You can *add* any kind of object into a `Collection`, but you can only add integers to `Collection`, so clearly `Collection` is not a supertype of `Collection`. Now try adding things to `Collection>` :) – Sweeper Aug 04 '22 at 13:37

0 Answers0