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?
A HashSet<T> is a class designed to give you O(1) lookup for containment (i.e., does this collection contain a particular object, and tell me the answer fast). A List<T> is a class designed to give you a collection with O(1) random access than can grow dynamically (think dynamic array).
By definition, a HashSet is not sorted. If you want a sorted hash set, then you should use a SortedSet . The methods it exposes are essentially a superset of those provided by HashSet , including the ability to sort its contents.
Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With