[C#]ArrayList初始容量
很多書都寫 ArrayList 的初始容量是16個元素,
但測試出來,看起來並不是這樣,超過 8 個元素,才開始為16的倍數。(有點傻,太執意在16了)
Allen老師講解,預設為4 ,之後*2
private static void Main(string[] args)
{
ArrayList none = new ArrayList();
Console.WriteLine(none.Capacity);
ArrayList one = new ArrayList();
one.Add(1);
one.Add(2);
Console.WriteLine(one.Capacity);
ArrayList two = new ArrayList();
two.Add(1);
two.Add(2);
two.Add(3);
two.Add(4);
two.Add(5);
Console.WriteLine(two.Capacity);
ArrayList three = new ArrayList();
three.Add(1);
three.Add(2);
three.Add(3);
three.Add(4);
three.Add(5);
three.Add(6);
three.Add(7);
three.Add(8);
three.Add(9);
three.Add(10);
three.Add(11);
three.Add(12);
three.Add(13);
three.Add(14);
three.Add(15);
three.Add(16);
three.Add(17);
three.Add(18);
three.Add(19);
three.Add(20);
Console.WriteLine(three.Capacity);
int capacity = 8;
ArrayList tmp = new ArrayList(capacity);
Console.WriteLine(tmp.Capacity);
tmp.TrimToSize();
Console.WriteLine(tmp.Capacity);
}
OutPut :
順便紀錄一下 ArrayList 可自訂初始容量,和調整到目前實際擁有元素的大小,加入元素的數量大於自訂,ArrayList 會自動調整容量。
如文章有錯誤,煩請告知,新人發帖請多包涵