C#에서 ArrayList를 생성할 때 초기 용량(initial capacity)을 지정하면, 요소가 추가될 때마다 내부 배열을 재할당하는 오버헤드를 줄여 성능을 개선할 수 있습니다. ArrayList 클래스의 생성자에 원하는 용량 값을 인수로 전달하면 됩니다.
지정된 초기 용량을 가진 ArrayList를 만드는 방법은 다음 코드와 같습니다.
예제 1
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list1 = new ArrayList(5);
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
Console.WriteLine("Capacity in ArrayList1 = "+list1.Capacity);
Console.WriteLine("Elements in ArrayList1...");
foreach (string res in list1) {
Console.WriteLine(res);
}
ArrayList list2 = new ArrayList(10);
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("Capacity in ArrayList2 = "+list2.Capacity);
Console.WriteLine("Elements in ArrayList2...");
foreach (string res in list2) {
Console.WriteLine(res);
}
Console.WriteLine("Is ArrayList1 equal to ArrayList2? = "+list1.Equals(list2));
list2.RemoveRange(3, 2);
Console.WriteLine("Elements in ArrayList2 after removing elements in a range...");
foreach (string res in list2) {
Console.WriteLine(res);
}
Console.WriteLine("Capacity in ArrayList2 = "+list2.Capacity);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Capacity in ArrayList1 = 5 Elements in ArrayList1... A B C D Capacity in ArrayList2 = 10 Elements in ArrayList2... A B C D E F G H I Is ArrayList1 equal to ArrayList2? = False Elements in ArrayList2 after removing elements in a range... A B C F G H I Capacity in ArrayList2 = 10
코드 설명
- new ArrayList(5) : 초기 용량이 5인 ArrayList를 생성합니다.
- Capacity 속성 : 현재 ArrayList가 저장할 수 있는 전체 요소 수를 반환합니다.
- RemoveRange(3, 2) : 인덱스 3부터 2개의 요소를 제거합니다.
- 요소를 제거한 후에도 Capacity 값은 그대로 유지되는 것을 확인할 수 있습니다.
예제 2
이번에는 Capacity와 Count 속성의 차이를 확인해 보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list = new ArrayList(5);
list.Add("A");
list.Add("B");
list.Add("C");
list.Add("D");
Console.WriteLine("Capacity in ArrayList = "+list.Capacity);
Console.WriteLine("Count of elements in ArrayList = "+list.Count);
Console.WriteLine("Elements in ArrayList...");
foreach (string res in list) {
Console.WriteLine(res);
}
list.Clear();
Console.WriteLine("Capacity in ArrayList = "+list.Capacity);
Console.WriteLine("Count of elements in ArrayList = "+list.Count);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Capacity in ArrayList = 5 Count of elements in ArrayList = 4 Elements in ArrayList... A B C D Capacity in ArrayList = 5 Count of elements in ArrayList = 0
핵심 정리
- Capacity는 ArrayList가 담을 수 있는 총 요소 수를 의미하고, Count는 실제로 저장된 요소 수를 의미합니다.
- Clear() 메서드를 호출하면 모든 요소가 제거되어 Count는 0이 되지만, Capacity 값은 변경되지 않습니다.
- 저장할 요소의 개수를 미리 알고 있다면 초기 용량을 지정하여 불필요한 메모리 재할당과 복사 작업을 방지하는 것이 좋습니다.