ใน C# คลาส ArrayList (อยู่ใน System.Collections) มีเมธอด Add() สำหรับเพิ่มรายการเดี่ยวที่ท้าย และ AddRange() สำหรับเพิ่มหลายรายการจากคอลเลกชันอื่นๆ พร้อมกัน
ตัวอย่างโค้ด: ใช้ Add() และ AddRange()
using System;
using System.Collections;
public class Demo
{
public static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add("Andy");
list.Add("Gary");
list.Add("Katie");
list.Add("Amy");
Console.WriteLine("Elements in ArrayList...");
foreach (string res in list)
{
Console.WriteLine(res);
}
// เพิ่มหลายรายการพร้อมกันด้วย AddRange()
string[] strArr = { "John", "Jacob" };
list.AddRange(strArr);
Console.WriteLine("Elements in ArrayList...UPDATED");
foreach (string str in list)
{
Console.WriteLine(str);
}
}
}
ผลลัพธ์
Elements in ArrayList...
Andy
Gary
Katie
Amy
Elements in ArrayList...UPDATED
Andy
Gary
Katie
Amy
John
Jacob
ตัวอย่างเพิ่มเติม: ใช้ AddRange() หลายครั้ง
using System;
using System.Collections;
public class Demo
{
public static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add("Andy");
list.Add("Gary");
list.Add("Katie");
list.Add("Amy");
Console.WriteLine("Elements in ArrayList...");
foreach (string res in list)
{
Console.WriteLine(res);
}
string[] strArr = { "John", "Jacob" };
list.AddRange(strArr);
Console.WriteLine("Elements in ArrayList...UPDATED");
foreach (string str in list)
{
Console.WriteLine(str);
}
string[] strArr2 = { "Tim", "Tom", "David" };
list.AddRange(strArr2);
Console.WriteLine("Elements in ArrayList...UPDATED");
foreach (string str in list)
{
Console.WriteLine(str);
}
}
}
ผลลัพธ์
Elements in ArrayList...
Andy
Gary
Katie
Amy
Elements in ArrayList...UPDATED
Andy
Gary
Katie
Amy
John
Jacob
Elements in ArrayList...UPDATED
Andy
Gary
Katie
Amy
John
Jacob
Tim
Tom
David
ข้อสังเกตสำคัญ
ArrayListเป็น non-generic collection - เก็บได้ทุกประเภท (object)Add()เพิ่มรายการเดี่ยว ใช้เวลา O(1) เฉลี่ย (amortized)AddRange(ICollection)เพิ่มหลายรายการพร้อมกัน มีประสิทธิภาพดีกว่าวนลูป Add()- ขยายขนาดอัตโนมัติเมื่อเต็ม (โดยค่าเริ่มต้น capacity = 0, แล้ว 4, 8, 16...)
- ในโค้ดสมัยใหม่ ควรใช้
List<T>แทน เพื่อ type safety และประสิทธิภาพที่ดีกว่า
เปรียบเทียบ ArrayList vs List<T>
| คุณสมบัติ | ArrayList | List<T> |
|---|---|---|
| Type Safety | ไม่มี (เก็บ object) | มี (generic) |
| Performance | ต้อง boxing/unboxing | ไม่ต้อง boxing |
| Namespace | System.Collections | System.Collections.Generic |