C#深入研究ArrayList动态数组自动扩容原理


1 void Test1() 2 { 3 ArrayList arrayList = new ArrayList(); 4 int length = 3; 5 for (int i = 0; i < length; i++) 6 { 7 arrayList.Add("TestData"); 8 } 9 Console.WriteLine("count = " + arrayList.Count); 10 Console.WriteLine("capacity = " + arrayList.Capacity); 11 }
1          static void Main(string[] args)
2         {
3             Test t = new Test();
4             t.Test1();
5             Console.ReadKey();
6         }        

新建一个Test 类,添加一个方法Test1(),添加如上代码,在main方法中调用。

输出结果为:count = 3

      capacity = 4

如果length = 0,输出结果为

      count = 0

      capacity = 0

如果length = 1,输出结果为

      count = 1

      capacity = 4

如果length = 4,输出结果为

      count = 4

      capacity = 4

如果length = 5,输出结果

      count = 5

      capacity = 8

先介绍下ArrayList的两个字段就不难理解为什么会输出这样的结果。

Count字段含义为动态数组的实际长度,Capacity含义为动态数组的实际容量,这两个字段的含义是不同的。我们借助反编译工具来一探究竟。

public virtual int Add(object value)
{
    if (this._size == this._items.Length)   //如果长度和容量相等,则调用EnsureCapacity方法       
    {
        this.EnsureCapacity(this._size + 1);
    }
    this._items[this._size] = value;
    this._version++;
    int num = this._size;
    this._size = num + 1;            //否则长度+1,容量不变
    return num;
}

这是ArrayList源码中的Add方法,_size相当于count, _items.Length相当于Capacity.我们把注意力放在这一行代码:

 this.EnsureCapacity(this._size + 1);
 1 private void EnsureCapacity(int min)
 2 {
 3     if (this._items.Length < min)
 4     {
 5         int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
 6         if (num > 0x7fefffff)
 7         {
 8             num = 0x7fefffff;
 9         }
10         if (num < min)
11         {
12             num = min;
13         }
14         this.Capacity = num;
15     }
16 }

把注意力放在第5行发现,如果容量为0,则设置为4,否则翻倍。

以上就是动态数组ArrayList自动扩容原理。