ArrayList.Capacity गुण आंतरिक सरणी का आकार प्राप्त या सेट करता है जो तत्वों को संग्रहीत करता है। क्षमता हमेशा Count से अधिक या बराबर होती है। क्षमता बढ़ाने से पुनः आवंटन कम होता है; घटाने से TrimToSize() कहा जाता है।
उदाहरण 1: डिफ़ॉल्ट क्षमता वृद्धि
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: प्रारंभिक क्षमता निर्दिष्ट करना
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
क्षमता को सेट करने से तुरंत आंतरिक सरणी का आकार बदल जाता है। यदि नई क्षमता Count से कम है, तो ArgumentOutOfRangeException फेंका जाता है। प्रदर्शन-महत्वपूर्ण परिदृश्यों में अपेक्षित आकार के लिए क्षमता पूर्व-आवंटित करें।