Udostępnij za pośrednictwem


ArrayList and List Collection Types

An ArrayList or List<T> object is a sophisticated version of an array. The ArrayList class and the List<T> generic class provides some features that are offered in most System.Collections classes but are not in the Array class. For example:

  • The capacity of an Array is fixed, whereas the capacity of an ArrayList or a List<T> is automatically expanded as required. If the value of the Capacity property is changed, the memory reallocation and copying of elements are automatically done.

  • ArrayList and List<T> provide methods that add, insert, or remove a range of elements. In Array, you can get or set the value of only one element at a time.

  • A synchronized version of ArrayList is easy to create using the Synchronized method. The Array class leaves it up to the user to implement synchronization.

  • ArrayList and List<T> provide methods that return read-only and fixed-size wrappers to the collection. Array does not.

On the other hand, Array offers some flexibility that ArrayList and List<T> do not. For example:

  • You can set the lower bound of an Array, but the lower bound of an ArrayList or a List<T> is always zero.

  • An Array can have multiple dimensions, while an ArrayList or a List<T> always has exactly one dimension.

  • An Array of a specific type (other than Object) has better performance than an ArrayList because the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur when storing or retrieving a value type. However, a List<T> can have similar performance to an array of the same type if no reallocations are required; that is, if the initial capacity is a good approximation of the maximum size of the list.

Most situations that call for an array can use an ArrayList or a List<T> instead; they are easier to use and, in general, have performance similar to an array of the same type.

Array is in the System namespace; ArrayList is in the System.Collections namespace; List<T> is in the System.Collections.Generic namespace.

See Also

Reference

ArrayList

System.Collections

List<T>

System.Collections.Generic

Array

Other Resources

Commonly Used Collection Types