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

Lớp ArrayList trong C# (Non-generic Collection)

ArrayList là collection non-generic (trước .NET 2.0), lưu trữ object, tự động resize. Namespace: System.Collections.

⚠️ Không khuyến khích dùng trong code mới. Hãy dùng List<T> (generic, type-safe, hiệu năng tốt hơn, không boxing/unboxing).

Các phương thức chính

Phương thứcMô tả
Add(object)Thêm phần tử vào cuối
AddRange(ICollection)Thêm nhiều phần tử từ collection khác
Clear()Xóa tất cả phần tử
Contains(object)Kiểm tra tồn tại
GetRange(index, count)Lấy đoạn con (sub-list)
IndexOf(object)Tìm index đầu tiên
Insert(index, object)Chèn tại vị trí
InsertRange(index, ICollection)Chèn nhiều phần tử
Remove(object)Xóa phần tử đầu tiên tìm thấy
RemoveAt(index)Xóa tại index
RemoveRange(index, count)Xóa đoạn
Reverse()Đảo ngược thứ tự
SetRange(index, ICollection)Ghi đè đoạn bằng collection khác
Sort()Sắp xếp (cần IComparable)
TrimToSize()Giảm Capacity = Count

Ví dụ: Sort ArrayList

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList arr = new ArrayList();
        arr.Add(89);
        arr.Add(34);
        arr.Add(77);
        arr.Add(90);
        
        Console.Write("Danh sách: ");
        foreach (int i in arr) Console.Write(i + " ");
        Console.WriteLine();
        
        arr.Sort(); // Sắp xếp tăng dần
        
        Console.Write("Đã sắp xếp: ");
        foreach (int i in arr) Console.Write(i + " ");
        Console.WriteLine();
        
        // Boxing/unboxing xảy ra ở đây: int → object → int
    }
}

Kết quả

Danh sách: 89 34 77 90
Đã sắp xếp: 34 77 89 90

So sánh ArrayList vs List<T>

Đặc điểmArrayListList<T>
Type safetyKhông (object)Có (T)
Boxing/UnboxingCó (value types)Không
Hiệu năngThấp hơnCao hơn
IntelliSenseHạn chếHoàn chỉnh
LINQ supportCần Cast<T>()Trực tiếp

Khi nào vẫn gặp ArrayList?

  • Code legacy (.NET Framework 1.x).
  • Interop với COM/Old API.
  • Cần lưu trữ nhiều kiểu khác nhau trong một list (hiếm, dùng List<object> thay thế).

Kết luận: Chỉ hiểu ArrayList để maintain code cũ. Code mới luôn dùng List<T>.