Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Thuộc tính Capacity của lớp ArrayList trong C#

Thuộc tính Capacity trong ArrayList lấy hoặc đặt số phần tử mà ArrayList có thể chứa. Capacity luôn lớn hơn hoặc bằng Count.

Dung lượng mặc định là 4. Khi thêm phần tử thứ 5, dung lượng tự động gấp đôi thành 8, và tiếp tục tăng theo cấp số nhân.

Ví dụ minh họa cơ chế tự động mở rộng

using System;
using System.Collections;

class Demo
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        arrList.Add(19);
        arrList.Add(44);
        arrList.Add(22);
        
        ArrayList arrList2 = new ArrayList();
        arrList2.Add(19);
        arrList2.Add(44);
        arrList2.Add(64);
        arrList2.Add(32);
        arrList2.Add(99); // Phần tử thứ 5
        
        Console.WriteLine("ArrayList1 - Total elements: " + arrList.Count);
        Console.WriteLine("ArrayList1 - Capacity: " + arrList.Capacity);
        Console.WriteLine("ArrayList2 - Total elements: " + arrList2.Count);
        Console.WriteLine("ArrayList2 - Capacity: " + arrList2.Capacity);
    }
}

Kết quả

ArrayList1 - Total elements: 3
ArrayList1 - Capacity: 4
ArrayList2 - Total elements: 5
ArrayList2 - Capacity: 8

Mẹo: Nếu biết trước số lượng phần tử ước lượng, dùng constructor new ArrayList(capacity) để tránh resize tốn kém nhiều lần.