ArrayList इंडेक्सर (this[int index]) के माध्यम से शून्य-आधारित इंडेक्स द्वारा तत्वों तक पहुंच प्रदान करता है। यह ऑब्जेक्ट्स संग्रहीत करता है, इसलिए किसी भी प्रकार के मान बॉक्स किए जाते हैं।
उदाहरण 1: तत्व पढ़ना
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
ArrayList गैर-जेनेरिक है और ऑब्जेक्ट्स संग्रहीत करता है। इंडेक्सर object लौटाता है, इसलिए मान प्रकारों को अनबॉक्सिंग की आवश्यकता होती है। अमान्य इंडेक्स ArgumentOutOfRangeException फेंकता है। आधुनिक कोड में List<T> पसंद किया जाता है।