Why this is wrong:
Class<? extends Number> type = Integer.class;
ArrayList<type> = new ArrayList<>();
?
Is there no way to instantiate a class of a specific type given a class object?
Obviously I would never do that directly, that is just an example to show what is needed. In the actual code I need I don't know the name of the type. For example
public void createAList(Class<? extends Number> type)
{
ArrayList<type> toReturn = new ArrayList<>();
return toReturn;
}
The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.
Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);
If you want to initialize Generic object, you need to pass Class<T> object to Java which helps Java to create generic object at runtime by using Java Reflection.
<T extends Number> ArrayList<T> createAList(Class<T> type)
{
ArrayList<T> toReturn = new ArrayList<>();
return toReturn;
}
ArrayList<Integer> intList = createAList(Integer.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