Create an Unknown Number of Arraylists

G

Guest

I would like to create an unknown number of ArrayLists, that is I don't know
that until runtime.

Of course I can do this if I knew I needed two:

ArrayList IntervalArray1 = new ArrayList();
ArrayList IntervalArray2 = new ArrayList();

but what if I don't know how many I need at build time?

Although the code below doesn't work, it expresses sorta what I would like
to do

for (int j = 0; j < onereader.FieldCount; j++)
{
ArrayList IntervalArray[j] = new ArrayList();
}

Any ideas? Some code to do it would be nice.

Thx
 
G

Guest

Andy said:
I would like to create an unknown number of ArrayLists, that is I don't know
that until runtime.

Of course I can do this if I knew I needed two:

ArrayList IntervalArray1 = new ArrayList();
ArrayList IntervalArray2 = new ArrayList();

but what if I don't know how many I need at build time?

Make an ArrayList of ArrayList's.

ArrayList IntervalArrays = new ArrayList();

and then at runtime N times:

IntervalArrays.Add(new ArrayList());

and use it as:

IntervalArrays[arrayno].Add(something);

and

IntervalArrays[arrayno][itemno]

Arne
 
L

Laurent Bugnion

Hi,
Andy said:
I would like to create an unknown number of ArrayLists, that is I
don't know that until runtime.

Of course I can do this if I knew I needed two:

ArrayList IntervalArray1 = new ArrayList();
ArrayList IntervalArray2 = new ArrayList();

but what if I don't know how many I need at build time?

Make an ArrayList of ArrayList's.

ArrayList IntervalArrays = new ArrayList();

and then at runtime N times:

IntervalArrays.Add(new ArrayList());

and use it as:

IntervalArrays[arrayno].Add(something);

and

IntervalArrays[arrayno][itemno]

Arne

You need to cast the content of ArrayLists before you use them, because
the content is defined as "object".

That would be:

( (ArrayList) IntervalArrays[arrayno] ).Add(something);

and

( (ArrayList) IntervalArrays[arrayno] )[itemno];

which is cumbersome to say the least. That's why you should rather use
List<> if you can

List<ArrayList> internalArrays = new List<ArrayList>();

HTH,
Laurent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top