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

时间:2023-03-09 03:29:26
C#深入研究ArrayList动态数组自动扩容原理
 1         void Test1()
{
ArrayList arrayList = new ArrayList();
int length = ;
for (int i = ; i < length; i++)
{
arrayList.Add("TestData");
}
Console.WriteLine("count = " + arrayList.Count);
Console.WriteLine("capacity = " + arrayList.Capacity);
}
          static void Main(string[] args)
{
Test t = new Test();
t.Test1();
Console.ReadKey();
}

新建一个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 + );
}
this._items[this._size] = value;
this._version++;
int num = this._size;
this._size = num + ;            //否则长度+1,容量不变
return num;
}

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

 this.EnsureCapacity(this._size + 1);
 private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == ) ? : (this._items.Length * );
if (num > 0x7fefffff)
{
num = 0x7fefffff;
}
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}

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

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