Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generics compilation error

I've the following generic class:

public class GenericClass<E,T extends Comparable<T>>
{
    public static <E, T extends Comparable<T>> GenericClass<E, T> create()
    {
        return new GenericClass<E, T>();
    }

    private GenericClass()
    {
    }
}

And this is how I simply use it:

GenericClass<MyClass, Double> set = GenericClass.create();

Eclipse compilation shows no errors, however - building with ant provides the following error:

MyClass.java:19: incompatible types; no instance(s) of type variable(s) E,T exist so that GenericClass<E,T> conforms to GenericClass<MyClass,java.lang.Double>
[javac] found   : <E,T>GenericClass<E,T>
[javac] required: GenericClass<MyClass,java.lang.Double>
[javac]             GenericClass<MyClass, Double> set = GenericClass.create();

Thanks!

like image 606
duduamar Avatar asked Feb 04 '11 09:02

duduamar


People also ask

Do generics prevent compile time errors?

Using generics in your Java development can help you detect issues during compile time rather than being confronted by them at run time. This gives you greater control of the code and makes the syntax easy to follow. Generics also improves code readability.

Are Java generics capable of preventing runtime error?

There are many advantages of using generics in Java. Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.

What causes compilation error?

Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps programmers debugging the source code.


1 Answers

Try using this:

      GenericClass<String, Double> set = GenericClass.<String,Double>create();

The Eclipse compiler and javac differ in their tolerance.

like image 197
Grzegorz Oledzki Avatar answered Oct 03 '22 17:10

Grzegorz Oledzki