How to create an array of ArrayLists in java?

13,423

Solution 1

You're creating an array of null references, so you need to initialize each of them to a new ArrayList<SMS>():

for (int i = 0; i < count; i++) {
    lists[i] = new ArrayList<SMS>();
}

Solution 2

int size = 9;
ArrayList<SMS>[] lists = new ArrayList[size];
for( int i = 0; i < size; i++) {
    lists[i] = new ArrayList<SMS>();
}
Share:
13,423
airbourne
Author by

airbourne

I am a student,

Updated on June 15, 2022

Comments

  • airbourne
    airbourne almost 2 years

    I am creating an array but cannot add values to it.

    ArrayList<SMS>[] lists = (ArrayList<SMS>[])new ArrayList[count];
    
            for(int i=0;i<temp.size();i++)
            {
                String number="",id="";
                number = temp.get(i).addr;
                id = temp.get(i).thread_id;
                lists[i].add(temp.get(i));            // Problem here
            }
    

    I am unable to add value to it