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)
Written by Ferhat Ziba
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Object creation
Authors
fero46
6.204K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#