Search code examples
javagenericstype-erasure

Getting Cannot convert from Set<MyObject> to Set<MyObject<?,?>>


Here is my code:

Set<MyObject<?, ?>> mySet = getSetOf(MyObject.class);

public <T> Set<T> getSetOf(Class<T> setClass) {
    Set<T> set = new HashSet<>();
    // ...
    return set;
}

So basically I want to write a method that returns a set of objects of specific class type. The compiler is complaining the return type of getSetOf(Class) is not the same as the declaration of mySet. If I change the declaration of mySet to Set<MyObject> mySet then it is happy. But I am following the practice to not using raw type to declare variable, hence parameterised it.

How do you resolve this?


Solution

  • If the Class<T> parameter is there purely for the type information of T, then it's unnecessary. You can return a generic Set<T>, and it will figure out what T is based on type inference.

    Set<MyObject<?,?>> mySet = getSet();
    
    public <T> Set<T> getSet() {
        Set<T> set = new HashSet<>();
        // ...
        return set;
    }
    
    class MyObject<T,U> {}
    

    Ideone Demo

    If you actually do need the Class<T> for the purposes of reflection, change it to Class<?> so that it doesn't affect the inferred type of T.