Create an array of ArrayList<String> elements
You cannot create an array of a generic type.
Instead, you can create an ArrayList<ArrayList<String>>
.
The correct way is:
ArrayList<String> name[] = new ArrayList[9];
However, this won't work either, since you can't make an array with a generic type, what you are trying to do is a matrix, and this should be done like this:
String name[][];
I know this is a bit old but I am going to respond to this anyway for future views.
If you really want an ArrayList<String>[]
structure, you can simply create a class that extends ArrayList and make an array of that class:
public class StringArrayList extends ArrayList<String>{}
And in your implementation:
ArrayList<String> name[] = new StringArrayList[9];
Here is a sample:
package testspace.arrays;
import java.util.List;
public class TestStringArray {
public static void main(String[] args) {
List<String>[] arr = new StringArrayList[10];
for(int i = 0; i < arr.length; i++){
// CANNOT use generic 'new ArrayList<String>()'
arr[i] = new StringArrayList();
for(int j = 0; j < arr.length; j++){
arr[i].add("list item #(" + j + "|" + i + ")");
}
}
StringBuilder sb = new StringBuilder();
for(final List<String> list : arr){
for(final String str : list){
sb.append(str + " ");
}
sb.append("\n");
}
System.out.println(sb.toString());
}
}
NOTE You will get a runtime error if you use this instead : arr[i] = new ArrayList<String>()