SoFunction
Updated on 2025-03-06

Usage and conversion methods of Array and ArrayList in C#

An overview of the difference between ArrayList and Array

ArrayList is a complex version of an array. The ArrayList class provides some functionality that is provided in most Collections classes but not in the Array class. For example:

The capacity of Array is fixed, while the capacity of ArrayList is automatically expanded as needed. If the value of the attribute is changed, memory reassignment and element copying are performed automatically.

ArrayList provides methods to add, insert or remove a range element. In Array, you can only get or set the value of one element at a time.

Use the Synchronized method to create a synchronized version of ArrayList easily. And Array will keep it until the user achieves synchronization.

Detailed explanation of the difference between ArrayList and Array: Full analysis of ArrayList

1. What is ArrayList

ArrayList is the legendary dynamic array. In the MSDN term, it is a complex version of Array. It provides the following benefits:

Dynamically increase and decrease elements

Implemented ICollection and IList interfaces

Flexible setting of array size

 

2. How to use ArrayList

The simplest example:

Copy the codeThe code is as follows:

ArrayList List = new ArrayList(); 
for( int i=0;i< 10;i++ ) //Add 10 Int meta-turbations to the array;Š//..The program does some processing
(5);//Remove the 6th element
for( int i=0;i< 3;i++ ) //Add 3 more meta-disorders (i+20);
Int32[] values ​​= (Int32[])(typeof(Int32));//Return the array contained in ArrayList

This is a simple example. Although it does not contain all the methods of ArrayList, it can reflect the most commonly used usage of ArrayList.

3. Important methods and properties of ArrayList

(1) Constructor

ArrayList provides three constructors:

    public ArrayList();

The default constructor will initialize the internal array with the default (16) size

    public ArrayList(ICollection);

Construct with an ICollection object and add elements of the collection to the ArrayList

    public ArrayList(int);

Initialize the internal array with the specified size

(2) IsSynchronized properties and methods

The IsSynchronized property indicates whether the current ArrayList instance supports thread synchronization, while the static method returns an ArrayList thread synchronization encapsulation.

If you use non-threaded synchronization instances, you need to call lock manually to keep thread synchronization when accessing multi-threads, for example:

Copy the codeThe code is as follows:

ArrayList list = new ArrayList(); 
//... 
lock( ) //When ArrayList is wrapped in non-thread, the SyncRoot property is actually itself, but in order to meet the SyncRoot definition of ICollection, SyncRoot is still used here to maintain the standardization of the source code.

( “Add a Item” ); 
}


If you use the instance returned by the method, you don’t need to consider the issue of thread synchronization. This instance itself is thread-safe. In fact, ArrayList implements an internal class that ensures thread synchronization. The returned instance of this class. Each property in it uses the lock keyword to ensure thread synchronization.

However, using this method() does not guarantee the synchronization of enumerations. For example, if one thread is deleting or adding a collection item, while another thread is enumerating at the same time, the enum will throw an exception. So, when enumeration, you must explicitly use SyncRoot to lock this collection.

Hashtable is similar to ArrayList for thread safety.

(3) Count attribute and Capacity attribute

The Count property is the number of elements currently contained in ArrayList, and this property is read-only.

The Capacity property is the maximum number that ArrayList can currently contain. This property can be set manually, but an exception will be raised when set to less than the Count value.

    (4)Add、AddRange、Remove、RemoveAt、RemoveRange、Insert、InsertRange

These methods are similar

The Add method is used to add an element to the end of the current list

The AddRange method is used to add a batch of elements to the end of the current list

The Remove method is used to delete an element and delete it through the reference of the element itself.

The RemoveAt method is used to delete an element and delete it by indexing the value.

RemoveRange is used to delete a batch of elements, and delete it by specifying the starting index and the number of deletes.

Insert is used to add an element to the specified position, and the elements behind the list are moved backwards in turn.

InsertRange is used to add a batch of elements from the specified position, and the elements behind the list are moved backwards in turn.

In addition, there are several similar methods:

The Clear method is used to clear all existing meta-mutations. The Contains method is used to find that an object is not in the list.

I won’t be burdened with the rest. You can check MSDN, which is more carefully mentioned above.

(5) TrimSize method

This method is used to fix the ArrayList to the size of the actual element. When the dynamic array element is determined not to be added, this method can be called to free up the spare memory.

(6) ToArray method

This method Copy the ArrayList element into a new array.

4. ArrayList and array conversion

Example 1:

Copy the codeThe code is as follows:

ArrayList List = new ArrayList(); 
(1); 
(2); 
(3); 

Int32[] values = (Int32[])(typeof(Int32));

Example 2:

Copy the codeThe code is as follows:

ArrayList List = new ArrayList(); 
(1); 
(2); 
(3); 

Int32[] values = new Int32[]; 
(values);

The above introduces two methods of converting from ArrayList to array

Example 3:

Copy the codeThe code is as follows:

ArrayList List = new ArrayList(); 
( “string” ); 
( 1 ); 
//Add different types of elements into the array

object[] values ​​= (typeof(object)); //Correct
string[] values ​​= (string[])(typeof(string)); //Error

It is different from an array, because it can be converted to an Object array, it will not make any mistake to add different types of elements into an ArrayList. However, when the ArrayList method is called, either pass a type or Object type that can be correctly transformed by all elements, otherwise an exception that cannot be transformed will be thrown.

5. Best suggestions for using ArrayList

In this section, we will discuss the difference between ArrayList and array, as well as the efficiency of ArrayList

(1) ArrayList is a complex version of Array

ArrayList encapsulates an Object-type array. In general, it has no essential difference from an array. Even many methods of ArrayList, such as Index, IndexOf, Contains, Sort, etc., directly call Array's corresponding methods based on internal arrays.

(2) The influence of internal Object type

For general reference types, this part has not a big impact, but for value types, adding and modifying elements into ArrayList will cause packing and unboxing operations, and frequent operations may affect some efficiency.

But for most people, most applications use arrays of value types.

There is no way to eliminate this impact. Unless you don’t use it, you will have to bear part of the efficiency loss, but this part of the loss will not be very large.

(3) Array expansion

This is a factor that has a greater impact on the efficiency of ArrayList.

Whenever methods such as Add, AddRange, Insert, InsertRange are executed, they will check whether the capacity of the internal array is insufficient. If so, it will rebuild an array at twice the current capacity, copy the old elements into the new array, and then discard the old array. The expansion operation at this critical point should be more influential in efficiency.

Example 1: For example, if a data with 200 elements is dynamically added to an ArrayList created with the default size of 16 elements, it will pass:

    16*2*2*2*2 = 256

Four expansions will meet the final requirements, so if:

    ArrayList List = new ArrayList( 210 );

Creating an ArrayList in the way will not only reduce the 4-time array creation and Copy operations, but also reduce memory usage.

Example 2: An ArrayList is created with an expected 30 elements:

    ArrayList List = new ArrayList(30);

During the execution process, if 31 elements are added, the array will be expanded to the size of 60 elements, and no new elements will be added in at this time. And if the TrimSize method is called, then there will be an expansion operation and 29 element size space is wasted. If at this time, use:

    ArrayList List = new ArrayList(40);

Then everything is solved.

Therefore, correctly estimating possible elements and calling the TrimSize method at appropriate times is an important way to improve the efficiency of ArrayList usage.

(4) The efficiency loss caused by frequent calls to IndexOf, Contains and other methods (Sort, BinarySearch and other methods have been optimized and are not in this column)

First of all, we need to be clear that ArrayList is a dynamic array, which does not include algorithms that quickly access through Key or Value. Therefore, in fact, calling IndexOf, Contains and other methods is a simple loop to execute to find elements. Therefore, frequent call to such methods is not faster than writing loops yourself and making some optimizations. If there are requirements in this regard, it is recommended to use a collection of key-value pairs such as Hashtable or SortedList.

Copy the codeThe code is as follows:

ArrayList al=new ArrayList(); 

("How"); 
("are"); 
("you!"); 

(100); 
(200); 
(300); 

(1.2); 
(22.8); 

......... 

//The first method to traverse the ArrayList object
foreach(object o in al) 

(()+" "); 


//The second method to traverse the ArrayList object
IEnumerator ie=(); 
while(()) 

(()+" "); 


//The third method to traverse the ArrayList object

I forgot, it seems to be using an attribute of the ArrayList object, which returns the number of elements in this object.

Then use the index

Copy the codeThe code is as follows:

for(int i=0;i< Count;i++) 

(al[i].ToString()+" "); 
}

ArrayList provides a method to return read-only and fixed-size wrappers to a collection. And Array doesn't offer it.

Array, on the other hand, provides some flexibility that ArrayList does not have. For example:

The lower limit of Array can be set, but the lower limit of ArrayList is always zero.

Array can have multiple dimensions, while ArrayList is always just one-dimensional.

Arrays of specific types (excluding Objects) perform better than ArrayList because elements of ArrayList are of the Object type, so packing and unboxing usually occur when storing or retrieving value types.

Most cases where an array is required can also be replaced by an ArrayList. It is easier to use and usually has similar performance to arrays of type Object.

Array is located in the System namespace; ArrayList is located in the namespace.

The above summarizes the difference between ArrayList and Array.