Last Updated: February 25, 2016
·
6.172K
· fero46

Create multiple objects in Java.

Let's assume we have a Human Class and two subtypes of Human: Man and Woman

public static List<Human> getInstances(Class<? extends Human> clazz, int counter)
{
    List humans = new ArrayList<Human>();
    for(int i=0;i< counter; i++)
    {
        humans.add(clazz.newInstance());
    }
    return humans;
}

Now you can use this for creating humans.

List<Men> men = Human.getInstances(Men.class,10);
List<Women> men = Human.getInstances(Women.class,10)

2 Responses
Add your response

Good tip. Probably want to change:

List humans = new ArrayList<Human>();

to

List humans = new ArrayList<Human>(counter);

more efficient because their won't be array reallocation as you go through the loop since size is known.

over 1 year ago ·

Interesting.
Another issue though: newInstance() requires some exceptions to be handled (InstantiationException, IllegalAccessException).

Apart from that, with the new streams in Java 8 this can be achieved in one go:
List<Human> result = Stream.generate(Woman::new).limit(10).collect(Collectors.toList());

over 1 year ago ·