SoFunction
Updated on 2025-03-01

How to use C#.Net ArrayList

ArrayList is the legendary dynamic array, which provides the following benefits:

  • Dynamically increase and decrease elements
  • Implement ICollection and IList interfaces
  • Flexible setting of array size

1. How to use ArrayList

The simplest example:

ArrayList List = new ArrayList(); 
for( int i=0;i<10;i++ ) //Add 10 Int elements to the array(i); 
//..The program does some processing(5);//Remove the 6th elementfor( int i=0;i<3;i++ ) //Add 3 more elements(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

2. 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);
Constructed 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:

ArrayList list = new ArrayList(); 
//... 
lock(  ) //When ArrayList is wrapped in non-thread, the SyncRoot property is actually itself.But to satisfyICollectionofSyncRootdefinition,Still use it hereSyncRoot来保持源代码of规范性 
{ 
( “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, which is deleted 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 elements.
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 free memory.

(6) ToArray method

This method Copy the ArrayList element into a new array.

3. ArrayList and array conversion

Example 1:

ArrayList List = new ArrayList(); 
(1); 
(2); 
(3); 
//When doing NHibernate, return IList to get an array (multi-dimensional), which can be implemented in the following way// string[] str=(string[])((ArrayList)ilist[0]).ToArray(Typeof(string)); 
Int32[] values = (Int32[])(typeof(Int32)); //Not working

Example 2:

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:

ArrayList List = new ArrayList(); 
( “string” ); 
( 1 ); 
//Add different types of elements into the arrayobject[] values = (typeof(object)); //correctstring[] values = (string[])(typeof(string)); //mistake

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 converted by all elements, otherwise an exception that cannot be transformed will be thrown.

4. Best advice on 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 the internal array.

(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 huge.

(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 );
Create 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 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 using ArrayList.

(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.

ArrayList al=new ArrayList(); 
("How"); 
("are"); 
("you!"); 
(100); 
(200); 
(300); 
(1.2); 
(22.8); 
......... 
//The first method to traverse the ArrayList objectforeach(object o in al) 
{ 
(()+" "); 
} 
//The second method to traverse the ArrayList objectIEnumerator ie=(); 
while(()) 
{ 
(()+" "); 
} 
//The third method to traverse the ArrayList objectI forgot,It seems to be use ArrayListAn attribute of an object,It returns the number of elements in this object. 
然后在use索引 
for(int i=0;i<Count;i++) 
{ 
(()+" "); 
} 

I hope this article introduces the usage method of ArrayList and will help you learn.