Reputation: 107
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
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
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
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
Reputation: 36476
An array of Object
s has elements initialized to null
(just like how an array of int
s 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