Array Lists

The classic problem with the Array type is its fixed size. If you do not know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).

Your program might be asking the user for input, or gathering input from a web site. As it finds objects (strings, books, values, etc.) you will add them to the array, but you have no idea how many objects you’ll collect in any given session. The classic fixed-size array is not a good choice, as you can’t predict how large an array you’ll need.

The ArrayList class is an array whose size is dynamically increased as required. ArrayLists provide a number of useful methods and properties for their manipulation. Some of the most important are shown in Table 9-3.

Table 9-3. ArrayList methods and properties

Method or Property

Purpose

Adapter(  )

Public static method that creates an ArrayList wrapper for an IList object.

FixedSize(  )

Overloaded public static method that returns a list object as a wrapper. The list is of fixed size; elements can be modified but not added or removed.

ReadOnly(  )

Overloaded public static method that returns a list class as a wrapper, allowing read-only access.

Repeat(  )

Public static method that returns an ArrayList whose elements are copies of the specified value.

Synchronized(  )

Overloaded public static method that returns a list wrapper that is thread-safe.

Capacity

Get Programming C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.