Click to See Complete Forum and Search --> : arraylist and classes


roguecoder
October 11th, 2009, 09:45 AM
had this problem for a while can't seem to get past it. i would love a fresh set of eyes.

its probably really easy but here we go anyway.

<code>

const int PLAYER = 0;
const int DEALER = 1;

private Pack pack = new Pack();
private ArrayList [] hands = new ArrayList[2];</code>

i am trying to place a variable like so

<code> this.hands[PLAYER].Add("hello"); </code>

but i get the following error

System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."


any help would be greatly appreciated.

darwen
October 11th, 2009, 12:07 PM
When you're doing


ArrayList [] hands = new ArrayList[2];


this initialises the array but not the elements (since ArrayList is a reference type).

So if you do


ArrayList [] hands = new ArrayList[2];
ArrayList hand = hands[0];


You'll find hand is null.

Therefore you have to do


ArrayList [] hands = new ArrayList[2];
hands[0] = new ArrayList();
hands[1] = new ArrayList();


Then you can add to the lists.

Or instead you can do this for shorthand :


ArrayList [] hands = new ArrayList [] { new ArrayList(), new ArrayList() };


Darwen.

roguecoder
October 12th, 2009, 07:12 AM
i knew it was going to be something simple thanks for the help..

i was trying to do this

hands[0].add(new ArrayList())

i never thought to use the = sign. :@

looking at it know it makes perfect sense why it wasn't working.

brain fart.

thanks again.