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

Lấy hoặc đặt số lượng phần tử ArrayList có thể chứa trong C#

Giới thiệu

ArrayList có hai khái niệm quan trọng: Count (số phần tử thực tế) và Capacity (số phần tử có thể chứa trước khi phải mở rộng bộ nhớ). Capacity tự động tăng gấp đôi khi cần.

Ví dụ 1: Quan sát Count và Capacity mặc định

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);
    }
}

Kết quả

Elements in ArrayList...
25
50
75
100
125
150
175
200
225
250
Count of elements = 10
Capacity = 16

Ví dụ 2: Khởi tạo với Capacity ban đầu

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);
    }
}

Kết quả

Elements in ArrayList...
25
50
75
100
Count of elements = 4
Capacity = 10

Quản lý Capacity hiệu quả

  • Khởi tạo với dung lượng dự kiến: new ArrayList(1000) tránh resize nhiều lần
  • TrimExcess(): Giảm Capacity xuống gần Count (tốn chi phí)
  • Capacity setter: Có thể gán trực tiếp arrList.Capacity = 50 (phải ≥ Count)
  • Mặc định Capacity = 0, tăng: 4 → 8 → 16 → 32 → 64...

Khuyến nghị hiện đại

Thay vì ArrayList, hãy dùng List<T> (generic) để tránh boxing/unboxing, an toàn kiểu và hiệu suất tốt hơn.