Giới thiệu
Lớp HashSet<T> cung cấp phương thức Contains(T item) để kiểm tra sự tồn tại của phần tử với độ phức tạp O(1) trung bình. Đây là cấu trúc dữ liệu lý tưởng cho việc kiểm tra thành viên (membership test) nhanh chóng.
Ví dụ 1
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet();
set1.Add(25);
set1.Add(50);
set1.Add(75);
set1.Add(100);
set1.Add(125);
set1.Add(150);
Console.WriteLine("Các phần tử trong HashSet1:");
foreach (int val in set1)
{
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add(30);
set2.Add(60);
set2.Add(100);
set2.Add(150);
set2.Add(200);
set2.Add(250);
Console.WriteLine("Các phần tử trong HashSet2:");
foreach (int val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("Hai tập hợp có phần tử chung? = " + set1.Overlaps(set2));
Console.WriteLine("HashSet1 có chứa phần tử 60? = " + set1.Contains(60));
Console.WriteLine("HashSet2 có chứa phần tử 60? = " + set2.Contains(60));
}
}
Kết quả
Các phần tử trong HashSet1 25 50 75 100 125 150 Các phần tử trong HashSet2 30 60 100 150 200 250 Hai tập hợp có phần tử chung? = True HashSet1 có chứa phần tử 60? = False HashSet2 có chứa phần tử 60? = True
Ví dụ 2
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet hashSet = new HashSet();
hashSet.Add("Tim");
hashSet.Add("Jack");
hashSet.Add("Matt");
hashSet.Add("Steve");
hashSet.Add("David");
hashSet.Add("Kane");
hashSet.Add("Gary");
Console.WriteLine("Các phần tử trong HashSet:");
foreach (string val in hashSet)
{
Console.WriteLine(val);
}
if (hashSet.Contains("Matt"))
Console.WriteLine("Phần tử 'Matt' có trong HashSet");
else
Console.WriteLine("Phần tử 'Matt' KHÔNG có trong HashSet");
}
}
Kết quả
Các phần tử trong HashSet Tim Jack Matt Steve David Kane Gary Phần tử 'Matt' có trong HashSet
Lưu ý quan trọng
Contains()của HashSet có độ phức tạp O(1) trung bình, nhanh hơn nhiều so với List/Array (O(n)).- HashSet tự động loại bỏ phần tử trùng lặp.
- Thứ tự phần tử trong HashSet không được đảm bảo.
- Đối với kiểu tự định nghĩa, bắt buộc override
GetHashCode()vàEquals()để đảm bảo đúng ngữ nghĩa tập hợp. - Có thể dùng
Overlaps()để kiểm tra giao nhau,SetEquals()để so sánh bằng nhau về nội dung.