When should I use the HashSet type?

前端 未结 11 1050
温柔的废话
温柔的废话 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 02:58

    Probably the most common use for hashsets is to see whether they contain a certain element, which is close to an O(1) operation for them (assuming a sufficiently strong hashing function), as opposed to lists for which check for inclusion is O(n) (and sorted sets for which it is O(log n)). So if you do a lot of checks, whether an item is contained in some list, hahssets might be a performance improvement. If you only ever iterate over them, there won't be much difference (iterating over the whole set is O(n), same as with lists and hashsets have somewhat more overhead when adding items).

    And no, you can't index a set, which would not make sense anyway, because sets aren't ordered. If you add some items, the set won't remember which one was first, and which second etc.

提交回复
热议问题