-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

1

4 Answers 4

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...

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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<>();

2 Comments

It actually specifically shouldn't be new ArrayList<Integer>[6] in this case. Also, the for each loop doesn't work for assignments.
@ZongLi re. second yes you're right, bad mistake on my part. re. first, really? I should learn how templates + arrays work I guess.
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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.