ภาพรวม
ArrayList มีคุณสมบัติ Capacity (ความจุภายใน) และ Count (จำนวนองค์ประกอบจริง) Capacity เพิ่มขึ้นอัตโนมัติเมื่อเพิ่มข้อมูลเกินขนาดปัจจุบัน สามารถตั้งค่า Capacity ได้เพื่อเพิ่มประสิทธิภาพ
ตัวอย่างที่ 1: เพิ่มข้อมูล 10 รายการ ดู Count และ Capacity
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList();
arrList.Add(25);
arrList.Add(50);
arrList.Add(75);
arrList.Add(100);
arrList.Add(125);
arrList.Add(150);
arrList.Add(175);
arrList.Add(200);
arrList.Add(225);
arrList.Add(250);
Console.WriteLine("Elements in ArrayList...");
foreach(int i in arrList)
{
Console.WriteLine(i);
}
Console.WriteLine("Count of elements = " + arrList.Count);
Console.WriteLine("Capacity = " + arrList.Capacity);
}
}
ผลลัพธ์
Elements in ArrayList...
25
50
75
100
125
150
175
200
225
250
Count of elements = 10
Capacity = 16
ตัวอย่างที่ 2: สร้าง ArrayList ด้วยความจุเริ่มต้น 10
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList(10);
arrList.Add(25);
arrList.Add(50);
arrList.Add(75);
arrList.Add(100);
Console.WriteLine("Elements in ArrayList...");
foreach(int i in arrList)
{
Console.WriteLine(i);
}
Console.WriteLine("Count of elements = " + arrList.Count);
Console.WriteLine("Capacity = " + arrList.Capacity);
}
}
ผลลัพธ์
Elements in ArrayList...
25
50
75
100
Count of elements = 4
Capacity = 10
คำอธิบายเพิ่มเติม
Capacityเป็นขนาดอาร์เรย์ภายใน Count <= Capacity เสมอ- เมื่อเพิ่มข้อมูลเกิน Capacity จะขยายอัตโนมัติ (ปกติคูณ 2) ซึ่งมีค่าใช้จ่ายในการจัดสรรหน่วยความจำและคัดลอก
- การตั้งค่า Capacity ใหญ่กว่า Count ล่วงหน้า ช่วยลดการขยายอาร์เรย์ซ้ำ (performance tuning)
- การตั้งค่า Capacity น้อยกว่า Count จะโยน ArgumentOutOfRangeException
- ArrayList เป็น non-generic แนะนำใช้
List<T>แทน