C#에서 ArrayList의 크기가 고정되어 있는지 확인하려면 IsFixedSize 속성을 사용합니다. 이 속성은 ArrayList의 크기가 고정되어 있으면 true, 그렇지 않으면 false를 반환하는 불리언(Boolean) 값입니다.
IsFixedSize 속성이란?
IsFixedSize는 읽기 전용 속성으로, 해당 컬렉션에 요소를 추가하거나 제거할 수 있는지 여부를 나타냅니다. 일반적인 ArrayList는 동적으로 크기가 조절되므로 기본값은 false이며, ArrayList.FixedSize() 메서드로 감싸면 크기가 고정된 래퍼(wrapper)가 반환되어 true가 됩니다.
예제 1: 기본 ArrayList 확인하기
다음 예제에서는 일반 ArrayList와 동기화된 ArrayList의 고정 크기 여부를 확인합니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list1 = new ArrayList();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("ArrayList의 요소...");
foreach (string res in list1) {
Console.WriteLine(res);
}
// 스레드로부터 안전한(동기화된) 래퍼 생성
ArrayList list = ArrayList.Synchronized(list1);
Console.WriteLine("ArrayList가 동기화되어 있는가? = " + list.IsSynchronized);
Console.WriteLine("ArrayList의 크기가 고정되어 있는가? = " + list.IsFixedSize);
}
}출력 결과
ArrayList의 요소... One Two Three Four Five ArrayList가 동기화되어 있는가? = True ArrayList의 크기가 고정되어 있는가? = False
위 결과에서 볼 수 있듯이, ArrayList.Synchronized()로 생성한 래퍼는 동기화되어 있지만(IsSynchronized = True) 크기는 고정되어 있지 않습니다(IsFixedSize = False). 즉, 동기화와 고정 크기는 서로 별개의 개념입니다.
예제 2: FixedSize() 메서드로 고정 크기 만들기
이번에는 ArrayList.FixedSize() 메서드를 사용하여 크기가 고정된 ArrayList를 만들고 확인해 보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list1 = new ArrayList();
list1.Add("ABC");
list1.Add("BCD");
list1.Add("CDE");
list1.Add("DEF");
list1.Add("EFG");
list1.Add("GHI");
list1.Add("HIJ");
list1.Add("IJK");
list1.Add("JKL");
list1.Add("KLM");
Console.WriteLine("ArrayList의 요소...");
foreach (string res in list1) {
Console.WriteLine(res);
}
ArrayList list = ArrayList.Synchronized(list1);
Console.WriteLine("ArrayList가 동기화되어 있는가? = " + list.IsSynchronized);
// 크기가 고정된 래퍼 생성
ArrayList list2 = ArrayList.FixedSize(list1);
Console.WriteLine("ArrayList의 크기가 고정되어 있는가? = " + list2.IsFixedSize);
}
}출력 결과
ArrayList의 요소... ABC BCD CDE DEF EFG GHI HIJ IJK JKL KLM ArrayList가 동기화되어 있는가? = True ArrayList의 크기가 고정되어 있는가? = True
핵심 정리
- IsFixedSize: ArrayList의 크기가 고정되어 있으면
true, 아니면false를 반환합니다. - ArrayList.FixedSize(): 기존 목록을 감싸는 고정 크기 래퍼를 반환합니다. 기존 요소의 수정은 가능하지만, 요소 추가(
Add)나 삭제(Remove)는 허용되지 않습니다. - ArrayList.Synchronized(): 멀티스레드 환경에서 안전하게 사용할 수 있는 동기화된 래퍼를 반환합니다.
- 고정 크기 목록에 요소를 추가하거나 제거하려고 하면
NotSupportedException이 발생합니다.
참고로, .NET 2.0 이상에서는 형식 안정성(type safety)과 성능 면에서 더 유리한 제네릭 컬렉션인 List<T> 사용이 권장됩니다. 다만 레거시 코드 유지보수 시에는 위와 같은 ArrayList의 속성과 메서드를 그대로 활용할 수 있습니다.