目录
该类在 System.Collections.Generic 命名空间。
HashSet<T> 类 表示值的集。
类型参数 T 表示哈希集中的元素类型。
HashSet<T> Constructors
该构造函数还有很多的重载形式 。这里列出常用的三种形式
public HashSet (); public HashSet (System.Collections.Generic.IEnumerable<T> collection); public HashSet (int capacity);
static void Main(string[] args) { // 调用默认构造函数,该实例为空并使用集类型的默认相等比较器 HashSet<int> evenNumbers = new HashSet<int>(); int[] number = { 55,55, 44, 33 ,33}; HashSet<int> evenNumbers1 = new HashSet<int>(number); foreach(var tt in evenNumbers1) { WriteLine(tt); // 输出 55 44 33 } WriteLine(); HashSet<int> evenNumber2 = new HashSet<int>(evenNumbers1); // evenNumber2 是 evenNumbers1 的副本 foreach (var tt in evenNumber2) { WriteLine(tt); // 输出 55 44 33 } HashSet<int> evenNumber3 = new HashSet<int>(10); // evenNumber3 的初始容量是10 }
Propertys
HashSet<T>.Comparer
public System.Collections.Generic.IEqualityComparer<T> Comparer { get; }
- 返回一个 IEqualityComparer<T> 对象,该对象用于确定集合中值的相等性。
HashSet<T>.Count
public int Count { get; }
- 获取集中包含的元素数。
static void Main(string[] args) { int[] number = { 55,55, 44, 33 ,33}; HashSet<int> evenNumbers1 = new HashSet<int>(number); // 输出3, 记住 HashSet 中的元素值不能是重复的,每一个元素值必须是唯一的 WriteLine(evenNumbers1.Count); }
Methods
HashSet<T>.Add
public bool Add (T item);
- 将名为 item 的元素添加到HashSet<T> 的尾部。
- 如果将元素添加到 HashSet <T> 对象中,则为true; 如果该元素已存在,则返回 false。
- 如果 Count已经等于 HashSet <T> 对象的当前容量,则会自动调整容量以容纳新的 item 元素。
- 如果Count小于内部数组的当前容量,则此方法为 o (1) 操作。 如果HashSet<T>对象必须调整大小,此方法将成为 O (
n
) 操作,其中n
是Count。int[] number = { 55,55, 44, 33 ,33}; HashSet<int> evenNumbers1 = new HashSet<int>(number); // 输出3, 记住 HashSet 中的元素值不能是重复的,每一个元素值必须是唯一的 evenNumbers1.Add(100); evenNumbers1.Add(200); foreach(var tt in evenNumbers1) { WriteLine(tt); }
HashSet<T>.Clear
public void Clear ();
- 从 HashSet<T> 对象中移除所有元素。并释放该集合所引用的内存。
- 此方法为 O (
n
) 操作,其中n
是Count。
HashSet<T>.Contains
public bool Contains (T item);
- 确定 HashSet<T> 对象是否包含名为 item 的元素。
- 如果 HashSet<T> 对象包含名为 item 的元素,则为
true
;否则为false
。- 此方法为 o (1) 运算。
static void Main(string[] args) { int[] number = { 55,55, 44, 33 ,33}; HashSet<int> evenNumbers1 = new HashSet<int>(number); evenNumbers1.Add(100); evenNumbers1.Add(200); if(evenNumbers1.Contains(55)) { WriteLine("包含"); } else WriteLine("不包含"); }
HashSet<T>.CopyTo
public void CopyTo (T[] array);
- 将当前的 HashSet<T> 对象的元素复制到一个名为 array 的T 类型的一维数组中。
如果参数 array
为null
。抛出 ArgumentNullException- 此方法为 O (
n
) 操作,其中n
是