-2

im having trouble making an array of arraylists, heres's the code :
'ArrayList<Integer>[] solucao= new ArrayList[6];' and using this code below:

           solucao[0].add(1);
            solucao[0].size();
                solucao[1].size();
                solucao[1].add(1);
            solucao[2].size();
            solucao[2].add(1);
                solucao[3].size();
                solucao[3].add(1);
            solucao[4].size();
            solucao[4].add(1);
                solucao[5].size();
                solucao[5].add(1);
            solucao[6].size();
            solucao[6].add(1);
                solucao[7].size();
                solucao[7].add(1);

all the calls for size return null. Anyone knows how to solve it?

Im looking for a data structure of array of arraylists, as each array[i] position will return me an arraylist of integers.

thank you

Futuregeek
  • 1,900
  • 3
  • 26
  • 51
enedois
  • 1
  • 1
  • you can check here http://stackoverflow.com/questions/10227201/initialize-an-array-of-arraylist to be precise ArrayList[] solucao = (ArrayList[])new ArrayList[10]; – GustyWind May 22 '13 at 05:05

4 Answers4

3

You have to initialize each ArrayList in the array.

ArrayList[] solucao = new ArrayList[6];
for (int i = 0; i < solucao.length; i++)
    solucao[i] = new ArrayList();

I actually thought you couldn't have an array of ArrayList. Apparently you can, but it must be non-generic. You should probably reconsider why you're doing this...

Zong
  • 6,160
  • 5
  • 32
  • 46
0
ArrayList<Integer>[] solucao= new ArrayList[6];

Should be new ArrayList<Integer>[6]

Note an IDE would give you a warning about this. Next, initialize each element of the array (Java 7):

for(int i = 0; i < solucao.length; i++) {
    solucao[i] = new ArrayList<>();
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • It actually specifically shouldn't be `new ArrayList[6]` in this case. Also, the for each loop doesn't work for assignments. – Zong May 22 '13 at 05:23
  • @ZongLi re. second yes you're right, bad mistake on my part. re. first, really? I should learn how templates + arrays work I guess. – djechlin May 22 '13 at 05:36
0

Arrays are just pointers or references. For each for them you have to create a new ArrayList object and store your data in it.

List[] solucao= new ArrayList[5];
for(int i=0;i<solucao.length;i++)
{
  solucao[i]  = new ArrayList();
  solucao[i].add(yourObject);
}
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

For store data first you have to create object.

ArrayList<Integer>[]  ls =  new ArrayList[7];
for (int i = 0; i < ls.length; i++) {
    ls[i] =  new ArrayList<Integer>();
    for(int j = 0 ; j<i ;j++){
        ls[i].add(j);   
    }
    System.out.println(ls[i].size());
}
kartavya soni
  • 91
  • 1
  • 8