In the previous <.net framework source code Research Series---Vest list> we studied together. NET in the list source code, also get some enthusiastic feedback from the brothers. One of them said he wanted to see ArrayList and LinkedList source code, so today is the topic, let's take a look. NET is how to implement ArrayList and LinkedList.
Let's look at the location of ArrayList and LinkedList in. NET, and the ArrayList namespace is the System.collections,linkedlist namespace is System.Collections.Generic , it seems that the two belong to the same collection class, but linkedlist in one branch. However, slightly right. NET source analysis, we will find that there is a clear difference between the two, can be said that there is a qualitative difference. These differences are not due to the different functions of the two, but to Microsoft's positioning them differently. In the. NET source physical structure, the ArrayList directory is "Redbits\ndp\clr\ Src\bcl\system\collections ", LinkedList's Directory is" Redbits\ndp\fx\src\compmod\system\collections\generic ". ArrayList belong to the CLR level, LinkedList is just an extra extension. So there is no comparison between the two.
Since there is no comparison between the two, we will look at how they are achieved. Look at the ArrayList first.
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];
These are the fields that are included in the ArrayList. Read the <.net framework Source code Research Series---Vest list> Yes, does the brother feel familiar?
Yes, actually ArrayList is the same as the list. The two are in the same CLR base class, and the implementation process is almost identical. But the two have different details.
First, the ArrayList is unconstrained, that is, the ArrayList can contain any type, and the list is strongly typed. Although both are essentially static methods that call array, such as copy, but in some ways ArrayList need to take a boxed unboxing operation, This can result in some performance loss, as follows:
public virtual int IndexOf(Object value){
return Array.IndexOf((Array)_items, value, 0, _size);
}
Second, ArrayList inherits the ICloneable interface, and the list does not.
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 above code we can see the ArrayList implementation of the shallow copy. There is a doubt that Microsoft's implementation of the Clone interface for ArrayList was intended to be a shallow copy rather than a deep copy.