Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Dynamic Arrays (ArrayList)

C# Dynamic Arrays (ArrayList)

C# Collection C# Collections

ArrayList is a dynamic array class provided in C#, located in the System.Collections namespace.

Unlike ordinary arrays, a dynamic array (ArrayList) can have its size adjusted dynamically, without the need to predefine a fixed length.

A dynamic array (ArrayList) represents an ordered collection of objects that can be individually indexed; it also allows dynamic memory allocation, addition, searching, and sorting of items in the list.

ArrayList The class is suitable for array operations that require frequent resizing, but due to its non-generic nature, it is gradually being replaced by List as a replacement.

Basic structure

public class ArrayList : ICollection, IEnumerable, IList, ICloneable

Implemented interfaces:

- `IList`: supports accessing elements by index. - `ICollection`: supports basic collection operations such as adding, removing, and counting. - `IEnumerable`: supports iterating over elements through an enumerator. - `ICloneable`: supports cloning `ArrayList`.

Feature

Dynamic Scaling:

Non-generic collection:

Unsorted operations:

Thread Safety:

Methods and properties of the ArrayList class

The following table lists the ArrayList Some commonly used members of the class property:

Attribute name Type Description
Count int Obtain the ArrayList the number of elements contained in ArrayList.
Capacity int Gets or sets the ArrayList capacity (storage space) of ArrayList.
IsFixedSize bool Indicates whether ArrayList ArrayList has a fixed size.
IsReadOnly bool Indicates whether ArrayList whether it is read-only.
IsSynchronized bool Indicates whether ArrayList whether it is thread-safe.
SyncRoot object Gets the object that can be used to synchronize access.

The following table lists the ArrayList Some commonly used members of the class Method:

Method Name Return Type Description
Adding and inserting
Add(object value) int Adds an object to the ArrayList end of ArrayList, returning the index of the new element.
AddRange(ICollection c) void Adds all elements of the specified collection to the ArrayList end of the
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 the specified number of elements starting from the specified index.
Clear() void Removes all elements.
Access and query
Contains(object item) bool Decision ArrayList Whether 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 according to the default order ArrayList elements in .
Sort(IComparer comparer) void Sorts according to a custom comparer.
Reverse() void Reverse ArrayList the order of the elements in ArrayList.
CopyTo(Array array) void data to the child component via ArrayList the elements of ArrayList to the specified array.
Others
GetRange(int index, int count) ArrayList Gets a subset of the specified number of elements starting from the specified index.
ToArray() object[] data to the child component via ArrayList the elements in ArrayList to an array.
TrimToSize() void Adjusts the capacity to the actual number of elements to save memory.

Example

The following example demonstrates the concept of a dynamic array (ArrayList):

Example

using

System

;

using

System.Collections

;

namespace

CollectionApplication

{

   

class

Program

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

// Create and initialize a dynamic array

            ArrayList numbers

=

InitializeArrayList

(

)

;

           

// Display the capacity and element count of the array

            DisplayArrayListInfo

(

numbers

)

;

           

// Display the contents of the array

            Console

.

Write

(

"Original Content: "

)

;

            DisplayArrayListContent

(

numbers

)

;

           

// Sort the contents of the array

            numbers

.

Sort

(

)

;

           

// Display the sorted contents

            Console

.

Write

(

"Sorted Content: "

)

;

            DisplayArrayListContent

(

numbers

)

;

            Console

.

ReadKey

(

)

;

// Wait for the user to press a key to exit

       

}

       

///

       

/// Initialize and populate the ArrayList

       

///

       

/// ArrayList containing initial data

       

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

;

       

}

       

///

       

/// Display the capacity and element count of the ArrayList

       

///

       

/// ArrayList object

       

static

void

DisplayArrayListInfo

(

ArrayList al

)

       

{

            Console

.

WriteLine

(

$

"\nCapacity: {al.Capacity}"

)

;

// Current capacity

            Console

.

WriteLine

(

$

"Count: {al.Count}"

)

;

       

// Current element count

       

}

       

///

       

/// Display the contents of the ArrayList

       

///

       

/// ArrayList object

       

static

void

DisplayArrayListContent

(

ArrayList al

)

       

{

           

foreach

(

int

num

in

al

)

           

{

                Console

.

Write

(

num

" "

)

;

           

}

            Console

.

WriteLine

(

)

;

// Newline

       

}

   

}

}

When the code above is compiled and executed, it produces the following result:


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 

Compared with generic List collections

Feature ArrayList List
Type Safety No (stores object type) Yes (generic, strongly typed constraints)
Boxing and unboxing Yes (required for value types) No
Performance Lower Higher
Generic Support None Yes
Use Cases Legacy code or simple scenarios Preferred in modern development

Notes

Avoid frequent boxing and unboxing:

Use mixed-type data with caution:

Alternatives:

C# Collection C# Collections