3

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?

Yoda
  • 17,363
  • 67
  • 204
  • 344

1 Answers1

6

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?).

Community
  • 1
  • 1
M A
  • 71,713
  • 13
  • 134
  • 174