Monday, May 5, 2008

ArrayList vs Array

While I was working with arrays I, in particular the array, I noticed something annoying. The annoying thing is that the array class in vb.net does not expose a delete or remove method. So, in order to remove an element you would have to use a For..Next loop to find the item, set it to Nothing and resize the array. vb.net being a powerful programming language should have a better and shorter way to do this. Well guess what?... There is!.
What would we use then?:

ArrayList


ArrayList exposes the remove method and will resize the array for you after you remove an item.

How does that work ?

Let's use our cars array again, but now, make it an arraylist.

(you need to use new so the cars will be an object of arraylist)
Dim cars As New ArrayList(3)

Now let's add some cars:

cars.Add("ford")
cars.Add("chevy")

cars.Add("dodge")

We don't even have to tell the index, now isn't that handy?!

Ok, now we want to remove the "chevy" from our cars arraylist.

We simply do this:

cars.Remove("chevy")

You can check the length of the cars arraylist using the count property. (cars.count) and you will see that it now contains 2 elements.

Hope you learned something new ;o)

No comments: