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

C# ArrayList에서 실제 포함된 요소 수 구하기 – Count 속성 완벽 정리

C#에서 ArrayList에 실제로 포함된 요소 수를 확인하려면 Count 속성을 사용하면 됩니다. Count는 현재 리스트에 저장되어 있는 요소의 개수를 반환하며, 내부적으로 할당된 저장 공간의 크기를 나타내는 Capacity와는 서로 다른 개념이라는 점을 먼저 이해하는 것이 중요합니다.

Count와 Capacity의 차이

  • Count: ArrayList에 실제로 추가된 요소의 개수를 반환합니다.
  • Capacity: 요소를 담기 위해 내부적으로 확보된 배열의 크기를 반환합니다.

요소를 계속 추가하면 Capacity는 필요에 따라 자동으로 늘어나지만, Count는 실제 저장된 요소 수만큼만 증가합니다. 따라서 리스트에 데이터가 몇 개 들어 있는지 알고 싶을 때는 항상 Count 속성을 사용해야 합니다.

예제 1: Count 속성으로 요소 수 확인하기

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args){
      ArrayList list1 = new ArrayList();
      list1.Add("A");
      list1.Add("B");
      list1.Add("C");
      list1.Add("D");
      list1.Add("E");
      list1.Add("F");
      list1.Add("G");
      list1.Add("H");
      list1.Add("I");
      Console.WriteLine("Elements in ArrayList1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      ArrayList list2 = new ArrayList();
      list2.Add("A");
      list2.Add("B");
      list2.Add("C");
      list2.Add("D");
      list2.Add("E");
      list2.Add("F");
      list2.Add("G");
      list2.Add("H");
      list2.Add("I");
      Console.WriteLine("Elements in ArrayList2...");
      foreach (string res in list2){
         Console.WriteLine(res);
      }
      ArrayList list3 = new ArrayList();
      Console.WriteLine("Current capacity of ArrayList3: " + list3.Capacity);
      list3 = list2;
      Console.WriteLine("Current capacity of ArrayList3 (Updated) " + list3.Capacity);
      Console.WriteLine("Is ArrayList3 equal to ArrayList2? = "+list3.Equals(list2));
      Console.WriteLine("Count of elements in ArrayList2 = " + list2.Count);
      list2.Clear();
      Console.WriteLine("Count of elements in ArrayList2 (Updated) = " + list2.Count);
   }
}

실행 결과

Elements in ArrayList1...
A
B
C
D
E
F
G
H
I
Elements in ArrayList2...
A
B
C
D
E
F
G
H
I
Current capacity of ArrayList3: 0 
Current capacity of ArrayList3: 16
Is ArrayList3 equal to ArrayList2? = True
Count of elements in ArrayList2 = 9 
Count of elements in ArrayList2 (Updated) = 0

결과 분석

위 출력 결과를 살펴보면 다음과 같은 사실을 확인할 수 있습니다.

  • list2에는 A부터 I까지 총 9개의 문자열이 저장되어 있으므로 Count 값이 9로 출력됩니다.
  • Clear() 메서드를 호출하여 모든 요소를 제거한 뒤에는 Count가 0으로 바뀌는 것을 볼 수 있습니다.
  • list3 = list2;처럼 참조를 할당하면 두 변수는 동일한 인스턴스를 가리키게 되므로 Equals() 비교 결과가 True가 됩니다.
  • 새로 생성한 list3은 초기 Capacity가 0이지만, list2의 참조를 받은 후에는 list2와 같은 내부 상태(16)를 공유하게 됩니다.

예제 2: Capacity와 함께 확인하기

이번에는 Capacity 값을 함께 출력하여 Count와의 차이를 더 명확하게 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args){
      ArrayList list1 = new ArrayList();
      list1.Add("A");
      list1.Add("B");
      list1.Add("C");
      list1.Add("D");
      list1.Add("E");
      list1.Add("F");
      list1.Add("G");
      list1.Add("H");
      list1.Add("I");
      Console.WriteLine("Current capacity of ArrayList1: " + list1.Capacity);
      Console.WriteLine("Elements in ArrayList1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      ArrayList list2 = new ArrayList();
      list2.Add("A");
      list2.Add("B");
      list2.Add("C");
      list2.Add("D");
      list2.Add("E");
      list2.Add("F");
      list2.Add("G");
      list2.Add("H");
      list2.Add("I");
      Console.WriteLine("Elements in ArrayList2...");
      foreach (string res in list2){
         Console.WriteLine(res);
      }
      ArrayList list3 = new ArrayList();
      list3 = list2;
      Console.WriteLine("Is ArrayList3 equal to ArrayList2? = "+list3.Equals(list2));
   }
}

실행 결과

Current capacity of ArrayList1: 16 Elements in ArrayList1...
A
B
C
D
E
F
G
H
I
Elements in ArrayList2...
A
B
C
D
E
F
G
H
I
Is ArrayList3 equal to ArrayList2? = True

9개의 요소만 추가했음에도 Capacity가 16으로 출력되는 것을 통해, ArrayList는 요소 추가 시 미리 여유 공간을 확보하는 방식으로 동작한다는 것을 알 수 있습니다. 이처럼 Count는 실제 데이터 개수를, Capacity는 할당된 전체 공간을 나타내므로 두 속성을 상황에 맞게 구분해서 사용하는 것이 좋습니다.