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?
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);
}
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With