Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parametrize object by the same type as the given object?

Tags:

java

generics

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?

like image 656
Yoda Avatar asked Jan 17 '26 03:01

Yoda


1 Answers

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

like image 120
M A Avatar answered Jan 19 '26 18:01

M A



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!