The usage and conversion of Array and ArrayList in C

  • 2020-05-09 19:12:05
  • OfStack

An overview of the differences 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. Such as:

The capacity of       Array is fixed, while the capacity of ArrayList is automatically expanded as needed. If you change the value of the ArrayList.Capacity attribute, memory reallocation and element replication are done automatically.

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

      can easily create a synchronized version of ArrayList using the Synchronized method. Array keeps 1 in sync until the user implements it.

      ArrayList and Array

1. What is ArrayList

      ArrayList is the legendary dynamic array, or complex version of Array as MSDN calls it, which offers the following benefits:

      dynamic addition and subtraction of elements

      implements the ICollection and IList interfaces

      flexibly sets the size of the array

 

2. How to use      

The simplest example of      :


ArrayList List = new ArrayList();  
for( int i=0;i< 10;i++ ) // Add to array 10 a Int Yuan turbulence List.Add(i);Š//.. A program to do 1 Some processing   
List.RemoveAt(5);// Will be the first 6 Element removal   
for( int i=0;i< 3;i++ ) // add 3 A yuan of turbulence  List.Add(i+20);  
Int32[] values = (Int32[])List.ToArray(typeof(Int32));// return ArrayList Contained array  

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

      3, ArrayList important methods and attributes

      (1) constructor

      ArrayList provides three constructors:

      public ArrayList();

The       default constructor will initialize the inner array at the default size (16)

      public ArrayList(ICollection);

      is constructed with an ICollection object and the elements of the collection are added to ArrayList

      public ArrayList(int);

      initializes the inner array with the specified size

      (2) IsSynchronized property and ArrayList.Synchronized method

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

If       is using a non-thread-synchronized instance, then it is necessary to manually call lock to maintain thread synchronization when multiple threads are accessed, for example:


ArrayList list = new ArrayList();  
//...  
lock( list.SyncRoot ) // when ArrayList When wrapping for non-threads, SyncRoot The property is itself, but for satisfaction ICollection the SyncRoot Definition, again, use SyncRoot To keep the source code normative   
{  
list.Add(  " Add a Item "  );  
} 

  if use ArrayList Synchronized method returns the instance, then you don't have to consider the problem of thread synchronization, the instance itself is thread-safe, actually ArrayList internal implementation guarantee thread synchronization inner class 1, ArrayList. Synchronized return is an instance of the class, it inside of each attribute is to use the lock keyword to ensure thread synchronization.

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

      Hashtable is similar to ArrayList in its use of thread safety.

      (3) Count attribute and Capacity attribute

The       Count attribute is the number of elements that ArrayList currently contains. This attribute is read-only.

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

      (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, by reference to the element itself

The       RemoveAt method is used to delete an element by means of an 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 an element to the specified location, with the elements following the list moving back in order

      InsertRange is used to add a batch of elements from the specified position, with the elements following the list moving back in order

In addition, there are several similar methods:

The       Clear method clears all the existing elements and the Contains method looks for an object that is not in the list

      and I'm not going to bother you with the rest of the 11, but you can look at MSDN, which is a little bit more detailed

      (5) TrimSize method

      this method is used to pin ArrayList to the size of the actual element. This method can be called to free free memory when dynamic array elements are determined not to be added.

      (6) ToArray method

      this method puts Copy elements of ArrayList into a new array.

      4, ArrayList and array conversion

      case 1:


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

Int32[] values = (Int32[])List.ToArray(typeof(Int32)); 

Example 2:


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

Int32[] values = new Int32[List.Count];  
List.CopyTo(values); 

Two methods of converting from ArrayList to an array are described above

      case 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)); // error  

  is not the same as array, because it can be converted to Object array, so it is not wrong to add different types of elements into ArrayList. However, when calling ArrayList method, either pass the type that all elements can be transformed correctly or Object type, otherwise an exception that cannot be transformed will be thrown.

      5, ArrayList recommendations for best use

In this section we discuss the difference between ArrayList and arrays, and the efficiency of ArrayList

      (1) ArrayList is a complex version of Array

      ArrayList internally encapsulates an array of Object type. In the sense of 1, there is no essential difference between ArrayList and an array. Many methods of ArrayList, such as Index, IndexOf, Contains, Sort, etc., call the corresponding methods of Array directly on the basis of the internal array.

      (2) internal effects of Object types

This part of the       does not have much impact on 1-like reference types, but for value types, adding and modifying elements to ArrayList will cause boxing and unboxing 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 do not use it, you will incur a loss of efficiency of part 1, which is not very large.

      (3) array expansion

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

      whenever Add, AddRange, Insert, InsertRange add elements such as method, will check whether the internal array capacity is not enough, if it is, it will double the current capacity to rebuild one array, and the old element Copy into the new array, then discarding the old array, in this critical point of expansion, is affecting the efficiency of the comparison should be.

      example 1: for example, a data that may have 200 elements is dynamically added to an ArrayList created at the default size of 16 elements, which will go through:

      16*2*2*2*2 = 256

      four times of expansion will meet the final requirements, so if 1 begins with:

      ArrayList List = new ArrayList( 210 );

Creating ArrayList in       way not only reduces group creation and Copy operations by four times, but also reduces memory usage.

      example 2:1 ArrayList is created with an estimated 30 elements:

      ArrayList List = new ArrayList(30);

During the execution of      , 31 elements are added, so the array will be expanded to the size of 60 elements. At this time, no new elements will be added, and if the TrimSize method is not called, then there will be one expansion operation and the space of 29 elements will be wasted. If so, use:

      ArrayList List = new ArrayList(40);

      so the 1 cut is done.

      therefore, correctly estimating possible elements and calling the TrimSize method when appropriate is an important way to improve the efficiency of ArrayList.

      (4) efficiency loss caused by frequent calls to IndexOf, Contains, etc. (Sort, BinarySearch, etc., which are optimized and not included)

      first of all, we want to clear 1 point, ArrayList is a dynamic array, it does not include Key or Value through the algorithm of fast access, so in fact call IndexOf, Contains method is to perform simple cycle to look for the element, so often call this kind of method does not write cycle than yourself and make a little optimization to fast, if you have this requirement, it is recommended to use Hashtable or SortedList collection of key/value pair.


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);  

.........  

// The first 1 Kind of traverse  ArrayList  Object method   
foreach(object o in al)  
{  
Console.Write(o.ToString()+" ");  
}  

// The first 2 Kind of traverse  ArrayList  Object method   
IEnumerator ie=al.GetEnumerator();  
while(ie.MoveNext())  
{  
Console.Write(ie.Curret.ToString()+" ");  
}  

// The first 3 Kind of traverse  ArrayList  Object method  

I forgot to use an attribute of the ArrayList object, which returns the number of elements in the object.

      then takes advantage of the index


for(int i=0;i< Count;i++)  
{  
Console.Write(al[i].ToString()+" ");  
} 

ArrayList provides a way to return read-only and fixed-size wrappers to a collection. Array does not.

On the other hand,       offers some flexibility that ArrayList does not. Such as:

      can have a lower limit of Array, but the lower limit of ArrayList is always zero.

      Array can have multiple dimensions, while ArrayList is always only 1-dimensional.

      specific type (Object excluded) Array performs better than ArrayList because ArrayList elements are of type Object, so boxing and unboxing usually occur when storing or retrieving value types.

      can also use ArrayList in most cases where an array is required. It is easier to use and generally has similar performance to arrays of type Object.

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

      the difference between ArrayList and Array is summarized above.


Related articles: