I have a class ListCreator<T> and a static method collectFrom() which fabricates an instance of this class. collectFrom() has a parameter List l and I would like to parametrize returned instance of the ListCreator with the same type as the specified List is.
Ideally I would like something like that:
public static ListCreator<T> collectFrom(List<T> l) {
return new ListCreator<T>(l);
}
but this is impossible so I am stuck with this:
public class ListCreator<T> {
List<T> l;
public ListCreator(List<T> l) {
this.l = l;
}
public static ListCreator collectFrom(List l) {
return new ListCreator(l);
}
}
Is there a better solution?
Genericize your method by introducing the type parameter in its definition:
public static <T> ListCreator<T> collectFrom(List<T> l) {
return new ListCreator<T>(l);
}
In fact, the type parameter declared in class ListCreator<T> { has no meaning for this method since it is static (see Static method in a generic class?).
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