C#에서 두 개의 ArrayList 객체가 같은지 확인하려면 Equals() 메서드를 사용합니다. 다만 ArrayList의 Equals()는 요소의 내용이 아니라 객체 참조, 즉 두 변수가 동일한 인스턴스를 가리키고 있는지를 기준으로 비교한다는 점에 유의해야 합니다.
예제 1: 동일한 참조를 가리키는 경우
아래 코드에서는 list3에 list2를 대입했으므로 두 변수는 같은 객체를 참조합니다. 따라서 Equals()의 결과는 True가 됩니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
ArrayList list1 = new ArrayList() { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
ArrayList list2 = new ArrayList() { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
Console.WriteLine("ArrayList1의 요소...");
foreach (string res in list1) {
Console.WriteLine(res);
}
Console.WriteLine("ArrayList2의 요소...");
foreach (string res in list2) {
Console.WriteLine(res);
}
ArrayList list3 = list2; // list2와 동일한 참조를 할당
Console.WriteLine("ArrayList3은 ArrayList2와 같은가? = " + list3.Equals(list2));
}
}
출력 결과
ArrayList1의 요소... A B C D E F G H I ArrayList2의 요소... A B C D E F G H I ArrayList3은 ArrayList2와 같은가? = True
예제 2: 내용은 같지만 별개의 객체인 경우
이번에는 요소 구성이 완전히 동일하지만 각각 독립적으로 생성된 두 ArrayList를 비교해 보겠습니다. 이 경우 Equals()는 False를 반환합니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
ArrayList list1 = new ArrayList() { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
ArrayList list2 = new ArrayList() { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
Console.WriteLine("ArrayList1의 요소...");
foreach (string res in list1) {
Console.WriteLine(res);
}
Console.WriteLine("ArrayList2의 요소...");
foreach (string res in list2) {
Console.WriteLine(res);
}
Console.WriteLine("ArrayList1은 ArrayList2와 같은가? = " + list1.Equals(list2));
}
}
출력 결과
ArrayList1의 요소... A B C D E F G H I ArrayList2의 요소... A B C D E F G H I ArrayList1은 ArrayList2와 같은가? = False
참고: 요소 값까지 비교하는 방법
객체 참조가 아니라 실제 요소 값을 기준으로 두 ArrayList를 비교하려면 LINQ의 SequenceEqual() 메서드를 활용할 수 있습니다.
using System;
using System.Collections;
using System.Linq;
public class Demo {
public static void Main(){
ArrayList list1 = new ArrayList() { "A", "B", "C" };
ArrayList list2 = new ArrayList() { "A", "B", "C" };
bool isEqual = list1.Cast<string>().SequenceEqual(list2.Cast<string>());
Console.WriteLine("두 ArrayList의 요소가 모두 같은가? = " + isEqual); // True
}
}
핵심 정리
Equals()는 두 ArrayList가 같은 인스턴스(참조)인지를 비교합니다.- 요소 내용이 완전히 같아도 별개의 객체라면
False가 반환됩니다. - 값 기준 비교가 필요하다면 LINQ의
SequenceEqual()을 사용하세요. - ArrayList는 .NET 초기 버전의 비제네릭 컬렉션이므로, 새 프로젝트에서는 형식 안정성이 뛰어난 제네릭 컬렉션
List<T>사용이 권장됩니다.