Otavio Macedo Otavio Macedo - 1 year ago 77
Java Question

guava-libraries: List with n instances

The Java

class has the following method:

static <T> List<T> nCopies(int n, T o)

I need a similar method, but slightly more generic, which provides n instances of a given class. Something like:

static <T> List<T> nInstances(int n, Supplier<T> supplier)

In particular, if
, we get the same behavior as the
method. Is there such a method somewhere in the Guava API?

Thank you.

Answer Source

No, but it's easy enough to implement:

public static <T> List<T> nInstances(int n, Supplier<T> supplier){
    List<T> list = Lists.newArrayListWithCapacity(n);
    for(int i = 0; i < n; i++){
    return list;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download