Petr Safar
Petr Safar

Reputation: 107

How to initialize the elements of an ArrayList?

How do I initialize the values of an ArrayList?

I found this on the internet, but it doesn't work.

ArrayList<Kaart>[] hand = (ArrayList<Kaart>[]) new ArrayList[AANTALSPELERS];

All elements of hand are null. I get a nullPointerException because of that. Kaart is a class I created. AANTALSPELERS is a private static final int.

Upvotes: 1

Views: 2659

Answers (4)

M S
M S

Reputation: 4093

you created a Array of AANTALSPELERS elements and each element can hold an ArrayList.

Since you have not added any ArrayList to the Array, the Array will have the default element null.

You also need to do something like this to populate the Array with ArrayList

for(int i = 0; i < hand.length; i++)
    hand[i] = new ArrayList();// or the arraylist you have

Upvotes: 0

John B
John B

Reputation: 32969

Consider using Guava's ListMultimap where the key is the index.

ListMultimap<Integer, Kaart>

It will take care of all the list initialization for you.

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236142

This is the correct way, using generics. Notice that the warning is unavoidable (you can use a @SuppressWarnings annotation if that's a problem):

ArrayList<Kaart>[] array = (ArrayList<Kaart>[]) new ArrayList[AANTALSPELERS];
for (int i = 0; i < AANTALSPELERS; i++)
    array[i] = new ArrayList<Kaart>();

Upvotes: 3

tskuzzy
tskuzzy

Reputation: 36476

An array of Objects has elements initialized to null (just like how an array of ints is initialized to zeros).

So before you can use the elements of the array, you have to initialize each element.

ArrayList[] al = new ArrayList[5];

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

Upvotes: 6

Related Questions