C# Dynamic Array (ArrayList)
ArrayList is a dynamic array class provided in C#, located in the System.Collections namespace.
Dynamic arrays (ArrayList) differ from ordinary arrays in that their size can be adjusted dynamically without needing to define a fixed length in advance.
Dynamic array (ArrayList) represents an ordered collection of objects that can be individually indexed, and it also allows dynamic memory allocation, addition, searching, and sorting of items within the list.
ArrayListThe class is suitable for array operations that require frequent resizing, but due to its non-generic nature, it is gradually being [replaced by List<T>] in modern C# development.List<T>replacement.
Basic Structure
public class ArrayList : ICollection, IEnumerable, IList, ICloneable
Implement interface:
- Implement interface:
IList: Supports accessing elements by index.ICollection: Supports basic collection operations, such as adding, removing, and counting.IEnumerable: Supports iterating over elements via an enumerator.ICloneable: Supports cloningArrayList。
Features
Dynamic extension:
ArrayListIts capacity can be automatically adjusted as needed, with no need to specify a fixed size.- When the number of added elements exceeds the current capacity,
ArrayListIt automatically increases capacity (usually doubling the original capacity).
Non-generic collections:
ArrayListIt is a non-generic collection, and all elements are stored asobjecttype. This means it can store objects of any type, but attention should be paid to the performance impact of boxing and unboxing.
Unordered operation:
- Although the order of element storage is the same as the order of addition, it does not provide built-in sorting functionality.
Thread Safety:
- It is not thread-safe by default. If a thread-safe [implementation is needed],
ArrayList, can useArrayList.SynchronizedThe method creates a thread-safe version.
Methods and properties of the ArrayList class
The table below listsArrayListSome common uses of the classProperty:
| Attribute Name | Type | Description |
|---|---|---|
Count | int | GetArrayListThe number of elements contained. |
Capacity | int | Get or setArrayListThe capacity (storage space). |
IsFixedSize | bool | IndicateArrayListWhether it has a fixed size. |
IsReadOnly | bool | IndicateArrayListWhether it is read-only. |
IsSynchronized | bool | IndicateArrayListWhether it is thread-safe. |
SyncRoot | object | Gets an object that can be used for synchronized access. |
The table below listsArrayListSome common uses of the classMethods:
| Method Name | Return Type | Description |
|---|---|---|
| Adding and inserting | ||
Add(object value) | int | Add the object toArrayListAt the end, returns the index of the new element. |
AddRange(ICollection c) | void | Adds all elements of the specified collection toArrayListthe end. |
Insert(int index, object value) | void | Inserts an object at the specified index. |
InsertRange(int index, ICollection c) | void | Inserts all elements of the specified collection at the specified index. |
| Delete | ||
Remove(object value) | void | Removes the first occurrence of the specified object. |
RemoveAt(int index) | void | Removes the element at the specified index. |
RemoveRange(int index, int count) | void | Removes a specified number of elements starting from the specified index. |
Clear() | void | Remove all elements. |
| Accessing and querying | ||
Contains(object item) | bool | Decision MakingArrayListWhether it contains the specified object. |
IndexOf(object value) | int | Gets the index of the first occurrence of the specified object. |
LastIndexOf(object value) | int | Gets the index of the last occurrence of the specified object. |
| Sorting and copying | ||
Sort() | void | Sorts in the default order.ArrayListThe elements inside. |
Sort(IComparer comparer) | void | Sorts according to a custom comparer. |
Reverse() | void | ReverseArrayListThe order of elements in |
CopyTo(Array array) | void | willArrayListCopy the elements to the specified array. |
| Other | ||
GetRange(int index, int count) | ArrayList | Gets a subset of a specified number of elements starting from the specified index. |
ToArray() | object[] | willArrayListCopy the elements in to the array. |
TrimToSize() | void | Adjusts the capacity to the actual number of elements to save memory. |
Example
The following example demonstrates the concept of dynamic arrays (ArrayList):
Example
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
// Create a dynamic array and initialize it
ArrayList numbers = InitializeArrayList();
// Display the array's capacity and element count
DisplayArrayListInfo(numbers);
// Display array contents
Console.Write("Original Content: ");
DisplayArrayListContent(numbers);
// Sort the array contents
numbers.Sort();
// Display sorted content
Console.Write("Sorted Content: ");
DisplayArrayListContent(numbers);
Console.ReadKey(); // Wait for user to press a key to exit
}
/// <summary>
/// Initialize and populate the ArrayList
/// </summary>
/// <returns>An ArrayList containing the initial data</returns>
static ArrayList InitializeArrayList()
{
ArrayList al = new ArrayList();
Console.WriteLine("Adding numbers to the ArrayList:");
// Add initial elements
int[] initialNumbers = { 45, 78, 33, 56, 12, 23, 9 };
foreach (int num in initialNumbers)
{
al.Add(num);
Console.WriteLine($"Added: {num}");
}
return al;
}
/// <summary>
/// Display the capacity and element count of ArrayList
/// </summary>
/// <param name="al">ArrayList object</param>
static void DisplayArrayListInfo(ArrayList al)
{
Console.WriteLine($"\nCapacity: {al.Capacity}"); // current capacity
Console.WriteLine($"Count: {al.Count}"); // Current element count
}
/// <summary>
/// Display the contents of the ArrayList
/// </summary>
/// <param name="al">ArrayList object</param>
static void DisplayArrayListContent(ArrayList al)
{
foreach (int num in al)
{
Console.Write(num + " ");
}
Console.WriteLine(); // newline
}
}
}
When the above code is compiled and executed, it produces the following results:
Adding numbers to the ArrayList: Added: 45 Added: 78 Added: 33 Added: 56 Added: 12 Added: 23 Added: 9 Capacity: 16 Count: 7 Original Content: 45 78 33 56 12 23 9 Sorted Content: 9 12 23 33 45 56 78
and generic collectionsList<T>comparison
| Features | ArrayList | List<T> |
|---|---|---|
| Type Safety | No (storageobjecttype) | Yes (generic, strongly typed constraint) |
| Boxing and unboxing | Yes (required for value types) | no |
| Performance | Relatively Low | Higher |
| Generic support | None | Yes |
| Use Case | Legacy code or simple scenarios | Preferred in modern development |
Notes
Avoid frequent boxing and unboxing:
- If the data mainly consists of value types, it is recommended to use [List<T>]
List<T>to avoid performance overhead.
Use mixed-type data with caution.:
- Try not to mix and store objects of different types, so as to reduce the risk of runtime errors.
Alternative solution:
- In modern C# development, it is recommended to use generic collections (such as
List<T>、Dictionary<TKey, TValue>) to improve the safety and efficiency of the code.