Do you think it is possible to create something similar to this?
private ArrayList increaseSizeArray(ArrayList array_test, GenericClass) { array_test.add(new GenericObject()); // instance of GenericClass return array_test; }
A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.
Java Generic Type Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.) K - Key (Used in Map)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With