Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a generic method when the collection<T> needs genericizing?

Tags:

java

java-8

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.

like image 277
Xiagua Avatar asked Mar 09 '26 12:03

Xiagua


1 Answers

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.

like image 79
Sweeper Avatar answered Mar 12 '26 03:03

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!