When should I use the HashSet type?

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

    HashSet is a set implemented by hashing. A set is a collection of values containing no duplicate elements. The values in a set are also typically unordered. So no, a set can not be used to replace a list (unless you should've use a set in the first place).

    If you're wondering what a set might be good for: anywhere you want to get rid of duplicates, obviously. As a slightly contrived example, let's say you have a list of 10.000 revisions of a software projects, and you want to find out how many people contributed to that project. You could use a Set and iterate over the list of revisions and add each revision's author to the set. Once you're done iterating, the size of the set is the answer you were looking for.

提交回复
热议问题