I want to create an array that contains ArrayList
I\'ve tried
ArrayList name[] = new ArrayList()[];
I have tried this without an error, even though I have putted a limit in the array less than the amount of items added:
package Testes.src;
import java.util.ArrayList;
import java.util.List;
public class Testes {
private List<String> name=new ArrayList<String>(1);
public Testes(){
for (int i = 1; i <= 100; i++) {
name.add("Teste"+Integer.toString(i));
}
for (int i = 0; i < name.size(); i++) {
System.out.println(name.get(i));
}
}
public static void main(String [] args)
{
Testes t1=new Testes();
}
}
ArrayList<ArrayList<String>> name= new ArrayList<ArrayList<String>>(/*capacity*/);
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[][];
// This is the not correct way
ArrayList<String> name[] = new ArrayList<String>()[];
// This is the correct way
ArrayList<String> list[] = new ArrayList[2];
list[0] = new ArrayList();
list[1] = new ArrayList();
list[0].add("Some String 11");
list[0].add("Some String 22");
list[1].add("Some String 1111");
list[1].add("Some String 2222");
I know this is an old post, but someone just asked the same question and since nobody has mentioned the following solution, here it is.
One way to get around it could be something like a 2d array (the recent question was about a 2d array or ArrayLists) of objects and then you should be able to put ArrayList references in the array. I have not tested it, but something like this should work.
Object [][] data = new Object[5][5];
data[0][0] = new ArrayList<String>(); // etc . . .
You cannot create an array of a generic type.
Instead, you can create an ArrayList<ArrayList<String>>
.