Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown compilation error with generics in Java

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.

like image 920
Sal Avatar asked Nov 23 '25 07:11

Sal


2 Answers

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.

like image 93
Reimeus Avatar answered Nov 24 '25 22:11

Reimeus


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();
like image 38
Yogendra Singh Avatar answered Nov 24 '25 21:11

Yogendra Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!