Reputation: 395
Suppose I have two methods:
public Set<String> method1()
public List<String> method2()
How do I make a generic method off this? Specifically, I'm looking to genericize the "Set" and "List".
Here's an attempt that didn't work:
public static <T extends Collection> T<String> genericMethod
It's showing a compiler error: Type "T" does not have type parameters.
Upvotes: 3
Views: 106
Reputation: 271070
As far as the signature goes, it would be
public static <T extends Collection<String>> T genericMethod() {
...
}
Presumably, genericMethod
is going to create an instance of T
at some point and return that, rather than just returning null
(that wouldn't be very useful, would it?), but there is no guarantee that T
has any constructors at all. And due to type erasure, the runtime wouldn't know what type to create anyway. To work around this, the method would also need to accept a parameter that tells it how to create a T
:
public static <T extends Collection<String>> T genericMethod(Supplier<? extends T> tSupplier) {
...
}
Now, rather than saying new T()
, which is invalid, you do tSupplier.get()
to get a T
.
If the caller wants a Set<String>
, for example, they would do:
Set<String> set = genericMethod(HashSet::new);
Note that the specific implementation of the collection is now specified by the caller, rather than hidden as an implementation detail of genericMethod
. This is inevitable, as the specific type of collection (T
) is now unknown to genericMethod
.
Upvotes: 6