关于ArrayList对象的容量Capacity
ArrayList是一个长度可变的数组,那么它的容量是怎么变化的呢?先看下面一段程序:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace AboutArrayList
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
int iCapacity = al.Capacity;
Console.WriteLine("al.Capacity = " + iCapacity.ToString());
Console.WriteLine();
for (int i = 0; i < 200; i++)
{
al.Add(i);
if (iCapacity != al.Capacity)
{
iCapacity = al.Capacity;
Console.WriteLine("i = " + i.ToString());
Console.WriteLine("al.Capacity = " + al.Capacity.ToString());
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace AboutArrayList
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
int iCapacity = al.Capacity;
Console.WriteLine("al.Capacity = " + iCapacity.ToString());
Console.WriteLine();
for (int i = 0; i < 200; i++)
{
al.Add(i);
if (iCapacity != al.Capacity)
{
iCapacity = al.Capacity;
Console.WriteLine("i = " + i.ToString());
Console.WriteLine("al.Capacity = " + al.Capacity.ToString());
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}
运行结果如下:
al.Capacity = 0
i = 0
al.Capacity = 4
i = 4
al.Capacity = 8
i = 8
al.Capacity = 16
i = 16
al.Capacity = 32
i = 32
al.Capacity = 64
i = 64
al.Capacity = 128
i = 128
al.Capacity = 256
i = 0
al.Capacity = 4
i = 4
al.Capacity = 8
i = 8
al.Capacity = 16
i = 16
al.Capacity = 32
i = 32
al.Capacity = 64
i = 64
al.Capacity = 128
i = 128
al.Capacity = 256
可以发现ArrayList的容量是成倍增长的。也就是说如果给ArrayList添加一项,但其内部数组已经没有空间了,ArrayList就会把内部数组的大小加倍倍,给新项腾出空间。
顺便记录一下重新设置数组大小的方法:
一、VB.NET代码
Dim intArray As New int(1,2,3);
ReDim int intArray(5);
ReDim int intArray(5);
二、C#代码
int [] intArray = {1,2,3};
int [] intArray2 = new int[6];
Array.Copy(intArray,intArray2,intArray.Length);
int [] intArray2 = new int[6];
Array.Copy(intArray,intArray2,intArray.Length);