问题描述:

My Java compiler javac 1.6.0_37 fails at compiling the following small program:

import java.util.*;

public class QueueTest {

public static void main( String args[] ) {

Queue<String> q = new LinkedList<String>();

}

}

The error message is:

QueueTest.java:5: incompatible types

found : java.util.LinkedList<java.lang.String>

required: Queue<java.lang.String>

Queue<String> q = new LinkedList<String>();

^

1 error

According to the documentation, LinkedList<E> implements Queue<E>, and this should compile. I was able to compile this code with javac 1.5.0_08. Also, you can take the generics out of the picture and the problem remains the same (it won't compile, even without generics).

My question is: anyone defends the position of this not being a bug?

网友答案:

Try doing explicitly:

java.util.Queue<String> q = new java.util.LinkedList<String>();

Note that when importing with package.* it is prone to overriding (if you have a class with the same name that you explicitly imported or in the working package):

From the docs:

A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

any top level type named n declared in another compilation unit of p.
any type named n imported by a type-import-on-demand declaration in c.
any type named n imported by a static-import-on-demand declaration in c.

What you have here is a type-import-on-demand declaration, which is shadowed by a single type import declaration

网友答案:

It compiles for me.

The only conclusion is that you have imported a Queue class other than java.util.Queue or imported a LinkedList other than java.util.LinkedList or both.

网友答案:

There must be some other bug because it compiles fine with ideone using Java 1.6.0.31:

import java.util.*;

class QueueTest {
    public static void main( String args[] ) {
        Queue<String> q = new LinkedList<String>();
    }
}

Do you have another class on your classpath such as java.util.Queue or java.util.LinkedList which is overriding the JDK one?

相关阅读:
Top