3

The following compilation error makes no sense to me, and I was hoping someone would be able to elucidate:

static public void main(String args[]) throws ZipException, IOException
{
    File file = new File("C:\\temp");
    ZipFile zip_file = new ZipFile(file);
    Enumeration<ZipEntry> entries = zip_file.entries();
}   

I get the following error: Type mismatch: cannot convert from Enumeration<capture#1-of ? extends ZipEntry> to Enumeration<ZipEntry>

In order to get the above code to compile, I had to replace the entries declaration to use the generics <? extends ZipEntry>. Why do I have to do this? Doesn't ZipEntry extend ZipEntry? (Isn't that vacuously true?) Why does the compiler complain about that?

If it helps, I'm using Java 7.03 with Eclipse Indigo 64 bit.

1
  • Wow, I can't believe I forgot to post the error code! Thanks for the catch.
    – Sal
    Oct 26, 2012 at 23:54

4 Answers 4

5

ZipFile.entries() returns an enumeration of extended ZipEntry types but is not confined to ZipEntry itself so you need to use:

Enumeration<? extends ZipEntry> entries = zip_file.entries();

This allows for other types such as JarEntry objects to be used in ZipEntry Enumerations.

2
  • JarEntry extends ZipEntry, so the following code would be legal: ZipEntry zip = new JarEntry(). This is contravariance, which is legal in java. The OP is asking why you can not use Enumeration<? extends ZipFile> to set a Enumeration<ZipFile> variable... which by the logic of contravariance should be legal. Oct 27, 2012 at 0:16
  • Covariance works normally for objects but not when they are used in generics.
    – Reimeus
    Oct 27, 2012 at 0:21
2

If you look closely(source code), it return Enumeration<ZipEntry> only as below:

     return new Enumeration<ZipEntry>() {
            private int i = 0;
            public boolean hasMoreElements() {
            .....
            .....

But return type is declared as public Enumeration<? extends ZipEntry> entries() { to relax the restriction on the return type. If you wish to override entries() method through your custom subclass of Zipfile, you may want to use one of the subclasses of the ZipEntry as return type from the same method i.e. ZipEntry

If you don't want to use generics, you may want to write as :

  @SuppressWarnings("rawtypes")
  Enumeration entries = zip_file.entries();
0
1
Make sure that the file exists and is accessible, you can also try this 

Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip_file.entries(); 
1

Use <Z extends ZipEntry> and replace all of the ? instances in you methods if you have any, with Z. You are not limited to Z, you can use any letter you like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.