An Iterator<? extends ZipEntry>
represents an iterator of an unknown type. The only thing we know about that type is that it is ZipEntry
or a subtype of ZipEntry
. In other words, it could be Iterator<ZipEntry>
, Iterator<JarEntry>
, or Iterator<SomeOtherSubclass>
in actuality.
Because of this, you can't be sure that Iterator<? extends ZipEntry>
can be assigned to a variable of type Iterator<ZipEntry>
. Sure, if it were Iterator<ZipEntry>
, then you could assign it, but it could also be Iterator<JarEntry>
, or Iterator<SomeOtherSubclass>
, in which case you can't. Foo<T>
and Foo<U>
are unrelated types, even if T
is a subclass of U
. Have a read at this for why this is true for List<T>
and List<U>
.
In this case though, this argument (from the linked post):
// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?
doesn't apply to Iterator
s, because you can only take things out of iterators, but not add things in. In fact, all the operations you can do on an iterators are safe, even if you were allowed Iterator<Animal> animals = dogs;
. However, the compiler simply doesn't check that the all the operations are safe automatically.
The way Java works is, when you use a generic type, you can say "Please let me assign Iterator<JarEntry>
to Iterator<ZipEntry>
, and don't allow me to use any of the operations that are unsafe". The syntax to do that, is:
Iterator<? extends ZipEntry> it = zf.entries().asIterator();
(This is called use-site variance.)
It is no coincidence that this "don't-allow-me-to-use-any-of-the-operations-that-are-unsafe" type is exactly the same as the return type of asIterator
.
Since Iterator
doesn't have any such unsafe operations, you get the exact same interface as a regular Iterator<ZipEntry>
.
Compare this to when you use this on a List
. You would not be able to add
anything to a List<? extends ZipEntry>
, for example.