Generic type as parameter in Java Method
Yes, you can.
private static <T> List<T> pushBack(List<T> list, Class<T> typeKey) throws Exception {
list.add(typeKey.getConstructor().newInstance());
return list;
}
Usage example:
List<String> strings = new ArrayList<String>();
pushBack(strings, String.class);
Old question but I would imagine this is the preferred way of doing it in java8+
public <T> ArrayList<T> dynamicAdd(ArrayList<T> list, Supplier<T> supplier) {
list.add(supplier.get());
return list;
}
and it could be used like this:
AtomicInteger counter = ...;
ArrayList<Integer> list = ...;
dynamicAdd(list, counter::incrementAndGet);
this will add a number to the list, getting the value from AtomicInteger's incrementAndGet
method
Also possible to use constructors as method references like this: MyType::new
simple solution!
private <GenericType> ArrayList increaseSizeArray(ArrayList array_test, GenericType genericObject)
{
array_test.add(new genericObject());
return ArrayList;
}