When should I use the HashSet type?

前端 未结 11 997
温柔的废话
温柔的废话 2020-11-28 02:21

I am exploring the HashSet type, but I don\'t understand where it stands in collections.

Can one use it to replace a List

11条回答
  •  有刺的猬
    2020-11-28 03:09

    HashSet is a data strucutre in the .NET framework that is a capable of representing a mathematical set as an object. In this case, it uses hash codes (the GetHashCode result of each item) to compare equality of set elements.

    A set differs from a list in that it only allows one occurrence of the same element contained within it. HashSet will just return false if you try to add a second identical element. Indeed, lookup of elements is very quick (O(1) time), since the internal data structure is simply a hashtable.

    If you're wondering which to use, note that using a List where HashSet is appropiate is not the biggest mistake, though it may potentially allow problems where you have undesirable duplicate items in your collection. What is more, lookup (item retrieval) is vastly more efficient - ideally O(1) (for perfect bucketing) instead of O(n) time - which is quite important in many scenarios.

提交回复
热议问题