1

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.

3

4 Answers 4

6

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

Comments

3

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

Comments

0

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.

Comments

0

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

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.