Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force a static generic method's return type?

Having a class hierarchy:

String child = null;
Object parent = child;

How do I force Sets.newHashSet(E...) to return a Set<Object> while passing String arguments?

like image 446
Atom 12 Avatar asked Jun 24 '15 10:06

Atom 12


2 Answers

You can specify generic return type with:

Sets.<Object>newHashSet(child);

Maybe it would be OK for you to return Set<? extends Object>, then you can write it as a return type:

public Set<? extends Object> myMethod() {
    return Sets.newHashSet(child);
}
like image 142
Dmitry Ginzburg Avatar answered Sep 25 '22 17:09

Dmitry Ginzburg


You pass the type argument explicitly to newHashSet:

Sets.<Object>newHashSet(child);

If the type argument isn't passed explicitly the type is inferred and in this case it's inferred to the wrong type, presumably String.

It seems you're using Guava's Sets. The method signature is the following:

public static <E> HashSet<E> newHashSet()

As you can see newHashSet() takes a type parameter E. The result is HashSet<E>. E is inferred to be String, but you've specified the method to return Set<Object>. The solution is to either help the compiler or loosen the restriction in the return type to Set<? extends Object>.

like image 45
ReyCharles Avatar answered Sep 21 '22 17:09

ReyCharles