Tuesday, April 16, 2024 03:58

Table of contents >> Data Structures > Array List

Array List

ArrayList is a dynamic array. What that means is that an ArrayList can have any amount of objects and of any type. This data structure was originally designed to simplify the processes of adding new elements into an array. Under the hood, an ArrayList is an array whose size is doubled every time it runs out of space. Doubling the size of the internal array is a very effective strategy that reduces the amount of element-copying in the long run. We won’t get into the proof of that here. The data structure is very simple to use:

The downside to the ArrayList data structure is that you must cast the retrieved values back into their original type:

The ArrayList has following important methods:

Add() – This appends a new element object to the end. We can keep adding elements to the collection until memory runs out. Example:

AddRange() – we can use this method to combine two ArrayLists. Internally, AddRange() uses the Array.Copy() or CopyTo() methods, which have better performance than some loops. Here is how we use it:

Clear() – You can call the instance method Clear() on your ArrayList. Internally, this calls the Array.Clear() method, which I explained in the previous lesson. Example:

Sort(), Reverse() – these methods do exactly what their name says: they sort an ArrayList, or reverse the order of their elements. Example:

Insert(), RemoveAt(), RemoveRange() – methods used to add or remove elements into an ArrayList. Remove() it uses a numeric index to specify which element you want to remove. RemoveRange() specifies a starting index from which it should start removing elements, and another numeric parameter, to specify how many elements should be removed. Example:

The most important property of ArrayLists is Count:

Count – returns the number of elements in an ArrayList.

ArrayList is a collection that is best avoided. But it is often used in older legacy programs – so it must be supported. Newer .NET Framework versions offer better collections, like Lists, of which we will learn in the future.

Tags: , ,

Leave a Reply

Follow the white rabbit