ภาพรวม
ArrayList รองรับการเข้าถึงองค์ประกอบผ่านดัชนี arrList[index] ใช้ได้ทั้งการอ่านและเขียน (get/set) คล้าย List แต่เป็น non-generic (เก็บ object)
ตัวอย่างที่ 1: อ่านค่าที่ดัชนี 5
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList();
arrList.Add("Laptop");
arrList.Add("Desktop");
arrList.Add("Notebook");
arrList.Add("Ultrabook");
arrList.Add("Tablet");
arrList.Add("Headphone");
arrList.Add("Speaker");
Console.WriteLine("Elements in ArrayList...");
foreach(string str in arrList)
{
Console.WriteLine(str);
}
Console.WriteLine("Element at index 5 = " + arrList[5]);
}
}
ผลลัพธ์
Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
ตัวอย่างที่ 2: อ่านและอัปเดตค่าที่ดัชนี
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList();
arrList.Add("Laptop");
arrList.Add("Desktop");
arrList.Add("Notebook");
arrList.Add("Ultrabook");
arrList.Add("Tablet");
arrList.Add("Headphone");
arrList.Add("Speaker");
Console.WriteLine("Elements in ArrayList...");
foreach(string str in arrList)
{
Console.WriteLine(str);
}
Console.WriteLine("Element at index 5 = " + arrList[5]);
arrList[5] = "SSD";
Console.WriteLine("Element at index 5 (Updated) = " + arrList[5]);
}
}
ผลลัพธ์
Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
Element at index 5 (Updated) = SSD
คำอธิบายเพิ่มเติม
- ดัชนีเริ่มต้นที่ 0 ถึง Count-1 เข้าถึงนอกช่วงโยน ArgumentOutOfRangeException
- ArrayList เก็บ
objectต้อง cast เมื่อใช้งาน (เช่น(string)arrList[5]) - การ set ค่าจะแทนที่ออบเจ็กต์เดิม ไม่ขยายขนาด
- ArrayList เป็น legacy สำหรับโค้ดใหม่ใช้
List<T>เพื่อ type safety และหลีกเลี่ยง boxing/unboxing