When should I use the HashSet type?

前端 未结 11 996
温柔的废话
温柔的废话 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:06

    A HashSet implements the ICollection interface:

    public interface ICollection : IEnumerable, IEnumerable
    {
        // Methods
        void Add(T item);
        void Clear();
        bool Contains(T item);
        void CopyTo(T[] array, int arrayIndex);
        bool Remove(T item);
    
        // Properties
       int Count { get; }
       bool IsReadOnly { get; }
    }
    

    A List implements IList, which extends the ICollection

    public interface IList : ICollection
    {
        // Methods
        int IndexOf(T item);
        void Insert(int index, T item);
        void RemoveAt(int index);
    
        // Properties
        T this[int index] { get; set; }
    }
    

    A HashSet has set semantics, implemented via a hashtable internally:

    A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

    What does the HashSet gain, if it loses index/position/list behavior?

    Adding and retrieving items from the HashSet is always by the object itself, not via an indexer, and close to an O(1) operation (List is O(1) add, O(1) retrieve by index, O(n) find/remove).

    A HashSet's behavior could be compared to using a Dictionary by only adding/removing keys as values, and ignoring dictionary values themselves. You would expect keys in a dictionary not to have duplicate values, and that's the point of the "Set" part.

提交回复
热议问题