Reputation: 1649
My question is that what is the need of HashSet<T>
when we have SortedSet<T>
! All HashSet's methods are available in SortedSet too, moreover SortedSet is advantageous as it provides collection already in sorted manner! Even then HashSet is present. For what is it useful then?
Upvotes: 64
Views: 62138
Reputation: 5921
This is about choosing the right tool for the job. Depends on the way you are going to use your collection.
This page has a nice table detailing the differences between various collection classes.
Below is an extract from that table concerning the collections you are asking about:
Collection | Ordering | Contiguous? | Direct Access? | Lookup | Manipulate | Notes |
---|---|---|---|---|---|---|
HashSet | Unordered | Yes | Via Key | Key: O(1) | O(1) | Unique unordered collection, like a Dictionary except key and value are same object. |
SortedSet | Sorted | No | Via Key | Key: O(log n) | O(log n) | Unique sorted collection, like SortedDictionary except key and value are same object. |
Note:
Upvotes: 59
Reputation: 436
Both HashSet<T>
and SortedSet<T>
are implementing interface ISet<T>
which is a data structure holding unique elements.
The main difference between them is the underlying data structure they use to store data.
HashSet<T>
uses a hash-table while SortedSet<T>
uses a red-black tree which is a balanced binary tree.
The HashSet<T>
which uses a hash table does the basic operations (i.e. Add, Remove, Search) faster than SortedSet<T>
as the complexity of HashSet<T>
is O(1) meaning it will do basic operations independent of the size of input data in a constant period of time while the complexity of SortedSet<T>
is log(N) meaning depend on the size of input it will do the basic operations logarithmic. for example if the size of your input data is 1,000 then then the program does the basic operations in 10 steps and if it is 1,000,000 the program does the basic operations in 20 steps.
Conclusion: Use HashSet<T>
if you don't need the elements to be sorted otherwise use SortedSet<T>
. It means Using HashSet<T>
is preferable unless you need sorting.
Upvotes: 31
Reputation: 78840
If you don't need sorting, you shouldn't use a class that does sorting because that means your application will be doing more work than it needs to. (It will make your app faster, in other words).
Upvotes: 84