duduamar
duduamar

Reputation: 3924

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!

Upvotes: 10

Views: 13645

Answers (2)

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24251

Try using this:

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

The Eclipse compiler and javac differ in their tolerance.

Upvotes: 8

cadrian
cadrian

Reputation: 7376

Your expression GenericClass.create() bears no indication of type, so the compiler cannot infer the real type of E and T. You need to change the prototype of your function to help the compiler.

The simplest way is to pass the classes.

Example:

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

    private GenericClass() {
    }
}

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

Upvotes: 0

Related Questions