You cannot create an instance of an array of a generic type using new
.
One alternative is this:
import java.lang.reflect.*;
import java.util.*;
public class Test
{
public static void main( String args[] )
{
List<String[]> x = ...;
List<List<String[]>> yElements = Arrays.asList(
(List<String[]>[])Array.newInstance(List.class, x.size()));
}
}
Related question: How to create a generic array in Java?. (The example there is about creating an instance of an array of a generic type parameter ... but the same approach applies here.)
However, I think that this whole question is based on an incorrect assumption.
I also want to tell you that I MUST have a fixed lenght list to store a List of String[ ] in a specific index of this List of Lists.
You don't HAVE TO have a fixed sized list. From the computational perspective, your code would work just fine with a non-fixed sized list ... provided that you don't add or remove list elements. (In fact, using Arrays.asList
to wrap an array won't stop some other code trying to add / remove elements ...) Anyway ... if you just make the implementation type ArrayList<ArrayList<ArrayList<String>>>
, then the generic array creation problem goes away.
In addition, I suspect that it is incorrect to use x.size()
as the size of yElements
. The size of yElements
probably should be determined by the number of x
instances there are going to be, not the size of a given x
instance.