How to use C. Net ArrayList

  • 2021-08-21 21:08:35
  • OfStack

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

Dynamic addition and reduction of elements ICollection and IList interfaces are implemented 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 to an array 10 A Int Element  
List.Add(i); 
//.. Programming 1 Some treatment  
List.RemoveAt(5);// Will be 6 Elements removed  
for( int i=0;i<3;i++ ) // Add again 3 Elements  
List.Add(i+20); 
Int32[] values = (Int32[])List.ToArray(typeof(Int32));// Return ArrayList Array contained  

This is a simple example that does not include all the methods of ArrayList, but reflects the most common usage of ArrayList

2. Important methods and attributes of ArrayList

(1) Constructor

ArrayList provides three constructors:

public ArrayList();
The default constructor will initialize the internal array at the default size (16)

public ArrayList(ICollection);
Construct with an ICollection object and add the elements of the collection to ArrayList

public ArrayList(int);
Initializes the internal array with the specified size

(2) IsSynchronized attribute and ArrayList. Synchronized method

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

If you use a non-threaded synchronous instance, you need to manually call lock to keep threads synchronized when accessing multiple threads, for example:


ArrayList list = new ArrayList(); 
//... 
lock( list.SyncRoot ) // When ArrayList When wrapping for non-threads, SyncRoot An attribute is actually itself, 
 But in order to satisfy ICollection Adj. SyncRoot Definition, which is still used here SyncRoot To keep the source code normative  
{ 
list.Add(  " Add a Item "  ); 
} 

If you use the instance returned by ArrayList. Synchronized method, you don't need to consider the problem of thread synchronization. This instance itself is thread-safe. In fact, ArrayList implements an internal class to ensure thread synchronization, and ArrayList. Synchronized returns an instance of this class. Every attribute in it uses lock keyword to ensure thread synchronization.

However, using this method (ArrayList. Synchronized) does not guarantee the synchronization of the enumeration, for example, if one thread is deleting or adding collection items while another thread is enumerating at the same time, the enumeration will throw an exception. Therefore, when enumerating, you must explicitly use SyncRoot to lock this collection.

Hashtable and ArrayList use thread safety in a similar way.

(3) Count attribute and Capacity attribute

The Count attribute is the number of elements currently contained in the ArrayList, which is read-only.
The Capacity attribute is the maximum number that ArrayList can contain at present. You can set this attribute manually, but when it is set to less than Count value, an exception will be thrown.

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

These methods are similar

The Add method is used to add 1 element to the end of the current list
The AddRange method is used to add 1 batch of elements to the end of the current list
The Remove method is used to delete 1 element by reference to the element itself
The RemoveAt method is used to delete 1 element by index value
RemoveRange is used to delete 1 batch of elements by specifying the starting index and the number of deletions
Insert is used to add 1 element to the specified position, and the elements at the end of the list move back in turn
InsertRange is used to add 1 batch of elements from the specified position, and the elements at the end of the list move back in turn
In addition, there are several similar methods:

The Clear method is used to clear all existing elements
The Contains method is used to find an object in or out of the list
Other I do not 11 burdensome, you can see MSDN, more carefully said above

(5) TrimSize method

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

(6) ToArray method

This method puts the element Copy of ArrayList into a new array.

3. ArrayList and Array Conversion

Example 1:


ArrayList List = new ArrayList(); 
List.Add(1); 
List.Add(2); 
List.Add(3); 
// Be doing NHibernate Returns when IList Array of ( Multidimensional ), It can be implemented in the following ways  
// string[] str=(string[])((ArrayList)ilist[0]).ToArray(Typeof(string)); 
Int32[] values = (Int32[])List.ToArray(typeof(Int32)); // It won't work  

Example 2:


ArrayList List = new ArrayList(); 
List.Add(1); 
List.Add(2); 
List.Add(3); 
Int32[] values = new Int32[List.Count]; 
List.CopyTo(values); 

The above describes two methods of converting from ArrayList to array

Example 3:


ArrayList List = new ArrayList(); 
List.Add(  " string "  ); 
List.Add( 1 ); 
// Add different types of elements to the array  
object[] values = List.ToArray(typeof(object)); // Correct  
string[] values = (string[])List.ToArray(typeof(string)); // Errors  

And array is not like, because it can be converted to Object array, in the past, adding different types of elements in ArrayList will not make mistakes, but when calling ArrayList method, either pass the type that all elements can be correctly converted or Object type, otherwise it will throw an exception that cannot be converted.

4. Best Use Recommendations for ArrayList

In this section 1, we will discuss the differences between ArrayList and arrays, and the efficiency of ArrayList

(1) ArrayList is a complex version of Array

An array of Object type is encapsulated in ArrayList, which is not essentially different from array in a general sense. Even many methods of ArrayList, such as Index, IndexOf, Contains, Sort, etc., directly call the corresponding methods of Array on the basis of internal array.

(2) The influence of the internal Object type

For reference types like 1, the impact of this part is not very great, but for value types, adding and modifying elements to ArrayList will cause packing and unpacking operations, and frequent operations may affect the efficiency of Part 1.

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

There is no way to eliminate this effect. Unless you don't use it, you will have to bear part 1 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 great influence on the efficiency of ArrayList.

Whenever Add, AddRange, Insert, InsertRange and other methods to add elements are executed, it will check whether the capacity of the internal array is not enough. If so, it will rebuild an array with twice the current capacity, put the old element Copy into the new array, and then discard the old array. The expansion operation at this critical point should affect the efficiency.

Example 1: For example, a piece of data that might have 200 elements dynamically added to an ArrayList created at the default size of 16 elements would go through:

16*2*2*2*2 = 256

Four expansions will meet the final requirements, so if 1 starts with:

ArrayList List = new ArrayList( 210 );
Creating an ArrayList in this way will not only reduce the number of group creation and Copy operations by 4 times, but also reduce memory usage.

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

ArrayList List = new ArrayList(30);
In 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 at this time. If TrimSize method is called, then there will be an expansion operation and the space of 29 elements will be wasted. If at this time, use:

ArrayList List = new ArrayList(40);
Then all the cuts are solved.

Therefore, it is an important way to improve the efficiency of ArrayList to correctly estimate the possible elements and call TrimSize method at an appropriate time.

(4) Efficiency loss caused by frequent calls to IndexOf, Contains and other methods (Sort, BinarySearch and other methods are optimized, but not listed here)

First of all, we should make it clear that, ArrayList is a dynamic array, which does not include the algorithm of fast access through Key or Value, so in fact, calling IndexOf, Contains and other methods is a simple loop to find elements, so calling such methods frequently is not faster than writing loops and optimizing them slightly. If there is a requirement in this respect, it is recommended to use the collection of key-value pairs such as Hashtable or SortedList.


ArrayList al=new ArrayList(); 
al.Add("How"); 
al.Add("are"); 
al.Add("you!"); 
al.Add(100); 
al.Add(200); 
al.Add(300); 
al.Add(1.2); 
al.Add(22.8); 
......... 
// No. 1 1 Species traversal  ArrayList  Method of object  
foreach(object o in al) 
{ 
Console.Write(o.ToString()+" "); 
} 
// No. 1 2 Species traversal  ArrayList  Method of object  
IEnumerator ie=al.GetEnumerator(); 
while(ie.MoveNext()) 
{ 
Console.Write(ie.Curret.ToString()+" "); 
} 
// No. 1 3 Species traversal  ArrayList  Method of object  
 I forgot , It seems to be   Utilization  ArrayList Object's 1 Attributes , It returns 1 Number of elements in this object . 
 And then using the index  
for(int i=0;i<Count;i++) 
{ 
Console.Write(al.ToString()+" "); 
} 

I hope this article on the use of ArrayList introduction to help you learn.


Related articles: