2

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?

4 Answers 4

2

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!");
Sign up to request clarification or add additional context in comments.

Comments

1

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!");

Comments

1

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

1 Comment

Question is for creating array of arrayList
0

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

1 Comment

Isn't the question <String>[] not <String[]>

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.