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

C# ArrayList에서 모든 요소 제거하기 – Clear() 메서드 활용법

C#의 ArrayList에서 모든 요소를 한 번에 제거하려면 Clear() 메서드를 사용하면 됩니다. 이 메서드는 컬렉션에 포함된 모든 항목을 삭제하며, 호출 직후 Count 속성 값은 0이 됩니다. 아래 예제를 통해 자세히 살펴보겠습니다.

예제 1

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();
      list3 = list2;
      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
Is ArrayList3 equal to ArrayList2? = True
Count of elements in ArrayList2 = 9
Count of elements in ArrayList2 (Updated) = 0

코드 설명

위 예제에서 주목할 부분은 list3 = list2; 구문입니다. 이 코드는 새로운 ArrayList를 만드는 것이 아니라 list2와 동일한 객체를 참조하도록 하는 것입니다. 따라서 list2.Clear()를 호출하면 두 변수가 함께 가리키는 같은 객체의 모든 요소가 제거되고, Count 값이 0으로 변경됩니다.

예제 2

이번에는 또 다른 예제를 통해 Clear() 메서드의 동작을 확인해 보겠습니다.

using System;
using System.Collections;

public class Demo {
   public static void Main(String[] args){
      ArrayList arrList = new ArrayList();
      arrList.Add("One");
      arrList.Add("Two");
      arrList.Add("Three");
      arrList.Add("Four");
      arrList.Add("Five");

      Console.WriteLine("Elements in ArrayList...");
      foreach (string res in arrList) {
         Console.WriteLine(res);
      }

      Console.WriteLine("Count of elements in ArrayList = " + arrList.Count);

      arrList.Clear();
      Console.WriteLine("Count of elements in ArrayList (Updated) = " + arrList.Count);
  }
}

출력 결과

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

Elements in ArrayList...
One
Two
Three
Four
Five
Count of elements in ArrayList = 5
Count of elements in ArrayList (Updated) = 0

정리

Clear() 메서드는 ArrayList의 모든 요소를 제거하는 가장 간단하고 효율적인 방법입니다. 요소를 하나씩 Remove()RemoveAt()으로 삭제하는 방식과 달리, 호출 즉시 컬렉션이 비워지고 Count가 0으로 설정됩니다. 단, ArrayList 객체 자체는 그대로 유지되므로 이후에도 계속해서 새로운 요소를 추가할 수 있다는 점을 기억해 두세요.