Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# List 용량(Capacity) 확인 방법과 Count와의 차이점

C#에서 List<T>용량(Capacity)은 리스트가 재할당 없이 저장할 수 있는 요소의 총 개수를 의미합니다. 리스트에 실제로 담긴 요소 수(Count)와는 다른 개념이며, 내부 배열의 크기를 나타냅니다.

리스트의 용량을 확인하려면 Capacity 속성을 사용하면 됩니다. 아래 예제를 통해 살펴보겠습니다.

예제 1: 두 리스트의 용량 확인

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list1 = new List<string>();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");
      list1.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      Console.WriteLine("Capacity of List1 = "+list1.Capacity);
      List<string> list2 = new List<string>();
      list2.Add("India");
      list2.Add("US");
      list2.Add("UK");
      list2.Add("Canada");
      list2.Add("Poland");
      list2.Add("Netherlands");
      Console.WriteLine("Elements in List2...");
      foreach (string res in list2){
         Console.WriteLine(res);
      }
      Console.WriteLine("Capacity of List2 = "+list2.Capacity);
      Console.WriteLine("Is List2 equal to List1? = "+list2.Equals(list1));
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Elements in List1...
One
Two
Three
Four
Five
Capacity of List1 = 8
Elements in List2...
India
US
UK
Canada
Poland
Netherlands
Capacity of List2 = 8
Is List2 equal to List1? = False

흥미로운 점은 요소가 5개뿐인 list1의 용량이 8이라는 것입니다. 이는 C#의 List<T>가 내부적으로 동적 배열을 사용하며, 공간이 부족해질 때 현재 크기의 약 2배씩 용량을 늘리기 때문입니다.

예제 2: Clear() 호출 후 Count와 Capacity 비교

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list = new List<string>();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list){
         Console.WriteLine(res);
      }
      Console.WriteLine("\nCount of elements in list = "+list.Count);
      Console.WriteLine("Capacity of List (updated) = "+list.Capacity);
      list.Clear();
      Console.WriteLine("\nCount of elements in list (updated) = "+list.Count);
      Console.WriteLine("Capacity of List now = "+list.Capacity);
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Elements in List1...
One
Two
Three
Four
Five
Count of elements in list = 5
Capacity of List (updated) = 8
Count of elements in list (updated) = 0
Capacity of List now = 8

Count와 Capacity의 차이

  • Count: 리스트에 실제로 포함된 요소의 개수를 반환합니다.
  • Capacity: 리스트가 내부 배열을 다시 할당하지 않고 수용할 수 있는 최대 요소 수를 반환합니다.

위 예제에서 Clear() 메서드를 호출한 후 Count는 0이 되었지만, Capacity는 여전히 8로 유지되는 것을 확인할 수 있습니다. 즉, Clear()는 요소만 제거할 뿐 내부 배열의 메모리까지 해제하지 않습니다. 만약 용량까지 줄이고 싶다면 TrimExcess() 메서드를 사용하거나, 새로운 리스트를 생성하여 할당하는 방법을 활용할 수 있습니다.