C#에서 두 HashSet<T> 객체가 같은지 확인해야 할 때는 Equals() 메서드를 사용할 수 있습니다. Equals() 메서드는 지정된 객체가 현재 객체와 동일한지 여부를 bool 값으로 반환합니다. 아래 예제를 통해 자세히 살펴보겠습니다.
예제 1: Equals() 메서드로 동일성 확인
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
HashSet<string> set1 = new HashSet<string>();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
set1.Add("E");
set1.Add("F");
set1.Add("G");
set1.Add("H");
Console.WriteLine("HashSet1의 요소...");
foreach (string res in set1) {
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("HashSet2의 요소...");
foreach (string res in set2) {
Console.WriteLine(res);
}
HashSet<string> set3 = new HashSet<string>();
set3 = set2;
Console.WriteLine("HashSet3은 HashSet2와 같은가? = " + set3.Equals(set2));
}
}위 코드에서 set3 = set2; 구문은 set2와 동일한 참조를 set3에 할당합니다. 즉, 두 변수가 같은 객체를 가리키기 때문에 Equals() 메서드의 결과는 True가 됩니다.
출력
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
HashSet1의 요소... A B C D E F G H HashSet2의 요소... John Jacob Ryan Tom Andy Tim Steve Mark HashSet3은 HashSet2와 같은가? = True
이번에는 서로 다른 요소를 가진 두 HashSet을 비교하는 두 번째 예제를 살펴보겠습니다.
예제 2: 서로 다른 집합 비교
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
HashSet<string> set1 = new HashSet<string>();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
set1.Add("E");
set1.Add("F");
set1.Add("G");
set1.Add("H");
Console.WriteLine("HashSet1의 요소...");
foreach (string res in set1) {
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("HashSet2의 요소...");
foreach (string res in set2) {
Console.WriteLine(res);
}
Console.WriteLine("HashSet2는 HashSet1과 같은가? = " + set2.Equals(set1));
}
}출력
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
HashSet1의 요소... A B C D E F G H HashSet2의 요소... John Jacob Ryan Tom Andy Tim Steve Mark HashSet2는 HashSet1과 같은가? = False
참고: 요소 내용을 기준으로 비교하기
Equals() 메서드는 객체의 참조(인스턴스)를 비교한다는 점에 유의해야 합니다. 만약 두 HashSet이 동일한 요소들을 담고 있는지 그 자체를 확인하고 싶다면, SetEquals() 메서드를 사용하는 것이 좋습니다. SetEquals()는 두 집합의 요소가 완전히 일치할 때 true를 반환하므로, 집합의 내용을 비교하는 데 훨씬 적합합니다.