Thursday, April 3, 2003

Building an Array

A question that comes up occasionally on the mailing lists revolves around how to manipulate arrays of things. The problem is that once created, arrays can't change size. But what if you don't necessarily know how big it'll be right off the bat. Here's my favorite way to deal with arrays.

ArrayList al = new ArrayList();


for (loop over some set of things)





Thing[] things =

  (Thing[]) al.ToArray(typeof(Thing));

In other words, System.ArrayList is a convenient way to keep track of a list of things that you can later turn into an array.

Even better is the fact that you can construct an ArrayList from any array, like so:

ArrayList list = new ArrayList(things);

And you can remove a particular item like this:


Combine these three things, and you have a convenient way to remove an item from a list: turn the array into an ArrayList, remove the item you care about, then turn it back into an array. Or use Add instead of Remove, and you've got a convenient way to append things.

1 comment:

  1. I am one year old in Java and this was just what I was looking for, simple and great article.