I would like to implement a generic method which does something akin to the following:
private <T> void addToSize(ArrayList<T> list, Class<T> type, int size) {
int currentSize = list.size();
for(int i = currentSize; i < size; i++) {
try {
list.add(type.newInstance());
} catch (InstantiationException e) {
logger.error("", e);
} catch (IllegalAccessException e) {
logger.error("", e);
}
}
}
The method above works for something like so:
ArrayList<Integer> test = new ArrayList<Integer>();
addToSize(test, Integer.class, 10);
but I also want it to work for…
ArrayList<ArrayList<Integer>> test = new ArrayList<ArrayList<Integer>>();
addToSize(test, ArrayList.class, 10); //Is this possible?
Is this possible?
You could use the factory pattern:
Then for your example (implemented anonymously):
The cool thing about this is the class doesn’t need a default constructor, and you could pass values into its constructor and/or use the builder pattern. The complexity of the
create()method implementation is arbitrary.