Code.IT Code.IT - 2 years ago 70
Java Question

Generic Method with initialization of Set

I want to create a generic method to combine sets.

public class CollectionsHelper {
public static Set<?> combineSets(Set<?> set1, Set<?> set2){
return Collections.unmodifiableSet(new HashSet<?>() {{
addAll(set1);
addAll(set2);
}});
}
}


But I get the compile error:


Wildcard type '?' cannot be instantiated directly

Answer Source

Use a generic type parameter instead of the wildcard:

public static <T> Set<T> combineSets(Set<T> set1, Set<T> set2)
{
    return Collections.unmodifiableSet(new HashSet<T>() {{
        addAll(set1);
        addAll(set2);
    }});
}

On second thought, I wouldn't use an anonymous HashSet sub-class instance. I'd prefer:

public static <T> Set<T> combineSets(Set<T> set1, Set<T> set2)
{
    HashSet<T> set = new HashSet<>(set1);
    set.addAll (set2);
    return Collections.unmodifiableSet(set);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download