. NET Framework source code Research Series-ArrayList and ArrayList

Source: Internet
Author: User

In the previous article <. NET Framework source code Research Series --- vest List>. NET List source code, also get some enthusiastic feedback from some brothers. one of them said he wanted to see the source code of ArrayList and javaslist. So today we will take a look at this topic. NET.

First, let's look at the ArrayList and history list in.. NET. The namespace of the ArrayList is System. collections, The namespace of the Collections list is System. collections. generic. In this case, the two belong to the Collection class, except that the sorted list is in a branch. however, it is slightly correct. NET source code analysis, we will find that there is a significant difference between the two, or even a qualitative difference. these differences are not because of their different functions, but because Microsoft positions them differently. in. in the NET source code physical structure, the directory where ArrayList is located is "redbits \ ndp \Clr \ src \ BCL \System \ Collections ", the Directory of the Collections list is" redbits \ ndp \Fx \ src \ CompMod \System \ Collections \ Generic,ArrayList belongs to the CLR level. The rule list is only an extra extension.So there is no significance for comparison between the two.

Because there is no comparative significance between the two, we will divide them into two parts to see how the two are implemented. first look at ArrayList.

Code

     public class ArrayList : IList, ICloneable
{
private Object[] _items;
private int _size;
private int _version;
[NonSerialized]
private Object _syncRoot;
private const int _defaultCapacity = 4;
private static readonly Object[] emptyArray = new Object[0];

The above is the field contained in the ArrayList. I have read the <. NET Framework source code Research Series --- vest List>, do you think you are familiar with it?

Yes, in fact, ArrayList and List are the same. The two belong to the same CLR basic class, and the implementation process is almost identical. But the two are still different in detail.

First, ArrayList has no type constraints, that is, ArrayList can contain any type, while List is strongly typed. although both are essentially calling static methods of Array, such as Copy, in some methods, ArrayList requires the binning operation, which may cause some performance loss. The following code:

         public virtual int IndexOf(Object value){
return Array.IndexOf((Array)_items, value, 0, _size);
}

Secondly, ArrayList inherits the ICloneable interface, while List does not.

Code

         public virtual Object Clone(){
ArrayList la = new ArrayList(_size);
la._size = _size;
la._version = _version;
Array.Copy(_items, 0, la._items, 0, _size);
return la;
}

 

 

From the code above, we can see the shortest copy of The ArrayList implementation. The question here is that Microsoft's original intention of implementing the clone interface for ArrayList is that it is a shortest copy instead of a deep copy.

 

After comparing the source code of ArrayList and List, I can roughly summarize the differences between them. Next, let's look at explain List.

Let's look at the definition first:

Code

 Public class Collections list <T>: ICollection <T>, System. Collections. ICollection, ISerializable, IDeserializationCallback {
Internal listnode <T> head;
Internal int count;
Internal int version;
Private Object _ syncRoot;
// A temporary variable used for deserialization
Private SerializationInfo siInfo;
/* Serialized name */
Const String VersionName = "Version ";
Const String CountName = "Count ";
Const String ValuesName = "Data ";

Public writable list (){}
Public parameter list (IEnumerable <T> collection ){
If (collection = null ){
Throw new ArgumentNullException ("collection ");
}

Foreach (T item in collection ){
AddLast (item );
}
}
Protected shortlist (SerializationInfo info, StreamingContext context) {siInfo = info ;}

The collections List implements the ICollection interface, indicating that it is a collection class. the implementation of the ISerializable interface indicates that it supports serialization by default, and also hides the implementation of the IEnumerable interface. at last, a less commonly used interface IDeserializationCallback is also supported, which enables the consumer list to execute certain actions before deserialization.

The ICollection and ISerializable functions of the ICollection list are not surprising. The implementation of IEnumerable is slightly different.. When it is the same as the ArralyList and List, an internal class Enumerator is used in the actual IEnumerable sequence List. Unlike the ArralyList, the List is different from the Enumerator in implementing IEnumerator, the IDeserializationCallback interface is also implemented during ISerializable. the other is for IEnumerator. the MoveNext method has different implementations. this is because the sort list is a two-way linked list, and the allocation space of each element in the set is not consecutive. It needs to be obtained through reference before and after. when we didn't add an object to the listing list, listing list will actually wrap the object we added as the listing listnode object, and this object has the Prev and Next attributes. this is easy to understand.

We just mentioned thatLinkedList also implementsIDeserializationCallbackInterface. For this, the following two points are required: 1, as described aboveIEnumerableThe interface is the same. This is because the pre-and post-reference of elements in the collection must be maintained during deserialization. Second, another method can be used to achieve this purpose. we know, actually. NET supports the following four methods by default for each serializable class:

OnDeserialized// Method executed when deserialization is completed

OnDeserializing// Method executed during deserialization

OnSerialized// Method of execution when serialization is complete

  OnSerializing// Method executed during serialization

With these four methods, we can do a lot of things, such as serializing objects that are not serializable. the private SerializationInfo siInfo field of the parameter list; it is actually used by OnDeserialized. let's take a look at how the solution List implements this method:

Code

         public virtual void OnDeserialization(Object sender){
if (siInfo == null){
return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it.
}

int realVersion = siInfo.GetInt32(VersionName);
int count = siInfo.GetInt32(CountName);

if (count != 0){
T[] array = (T[])siInfo.GetValue(ValuesName, typeof(T[]));

if (array == null){
throw new SerializationException(SR.GetString(SR.Serialization_MissingValues));
}
for (int i = 0; i < array.Length; i++){
AddLast(array[i]);
}
}
else{
head = null;
}
version = realVersion;
siInfo = null;
}

Actually, people who have used LinkeList know that the linked list is a two-way linked list and a collection. if you implement the same linked list, the implementation process is almost the same. the implementation of Microsoft's shortlist is also the same as that of everyone. The difference is the one mentioned above. as a set, the shortlist pairICollectionThe implementation of the interface is the same as that of the ArrayList interface.ICollectionInterface, and other unique methods should focus on maintaining the Prev and Next attributes of each element in the linked list. The implementation code is not listed here.

 

Summary

After the previous article <. NET Framework source code Research Series --- vest List> in this article, I think Microsoft is not actually a mysterious thing. Do the same thing, regardless of the thinking process or implementation method, similar to ours. the difference is more about details, suchIEnumerableTo IDeserializationCallbackIn our actual work, we can refer to Microsoft's practices or follow our own methods. In fact, there is no quality difference.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.