js_al
js_al

Reputation: 23

How to add an item to an array of array list

I'm trying to add a string to an array of array lists.

ArrayList<String>[] test = (ArrayList<String>[]) new ArrayList[2];
    test[0].add("Hello World!");

When the code above is executed, a null pointer exception is thrown. Any ideas how this can work?

Upvotes: 2

Views: 3368

Answers (4)

Santhosh
Santhosh

Reputation: 8217

You should create a new array each time when you are trying to add into the list,

String[] test= new String[2];    
ArrayList<String[]> test= new ArrayList<String[]>();    
t2[0]="0";
t2[1]="0";
test.add(t2); 

in the example above you are passing the reference of the test array object to the list.On each .add() method

or same thing can also be done in the below way in a single statement,

ArrayList<String>[] test = (ArrayList<String>[]) new ArrayList[2];
test.add(new String[] {"0", "0"});

Update

If you are trying to create array of arraylist have look here ,

Create an Array of Arraylists

Upvotes: 0

Kirtan
Kirtan

Reputation: 1812

you are using wrong syntax

it should work like this

ArrayList<String>[] arrayList = new ArrayList[2];
arrayList[0] = new ArrayList<String>();
arrayList[0].add("Hello World");

Upvotes: 1

Adam
Adam

Reputation: 36743

Your code is null pointering because array 'test' only contains a null references of type ArrayList. Your construction only creates the array storage, not the list storage. This is important to understand and is the same for any array of Objects (or Collection of Collections).

For example the following will contain 3 cells all which contain null.

Integer[] foo new Integer[3]

You need to instantiate a list before you can add to it.

ArrayList<String>[] test = (ArrayList<String>[]) new ArrayList[2];

test[0] = new ArrayList<String>();
test[0].add("Hello World!");

Upvotes: 2

Sangeeth
Sangeeth

Reputation: 634

For creating an array of ArrayList. You have to do the following

ArrayList[] test =  new ArrayList[2];// create array with all elements null
    for(int i=0; i<2;i++)
    {
        test[i] = new ArrayList<String>(); // initialize each element with ArrayList object
    }
    test[0].add("Hello World!");

Upvotes: 1

Related Questions