How to create a generic array in Java?
In Java, it is not possible to create a generic array directly. However, you can create an array of a specific type and then cast it to a generic type.
Here's an example:
List<String>[] array = (List<String>[])new List[10];
This creates an array of type List<String>[]
with a length of 10.
Keep in mind that this technique can cause a ClassCastException
at runtime if the generic type of the array is not used correctly.
Alternatively, you can use a generic collection class, such as ArrayList, to create a resizable array of a specific type.
Here's an example:
List<String> list = new ArrayList<>();
This creates an ArrayList of type String
that you can add and remove elements from dynamically.