HashSet Data Structure
Premium Content - Free Preview
The HashSet is a Set class in Java that uses a hash table internally. The HashSet is able to add, find and remove items in constant time, so it can solve many problems in an optimal manner. (Ruby and Python provide the same capabilities with their Set classes.)
A HashSet is a good choice whenever you have a large set of items and need to quickly check if a given item is in the set or not. We already saw that this can be used to detect duplicate data as you go through a list of numbers. It is often used to check live user data against established data for matches. For example, a Spell Checker that checks words as a user types them needs to extremely fast, so it uses a HashSet of real words to check if a given word is real or not. Here's a list of different cases where a HashSet could be used:
application | goal | what's in the set |
---|---|---|
spell checker | highlight misspelled words | correctly spelled words |
tic-tac-toe | detect victory | victory positions |
website blacklist filter | check if site is banned | blacklisted domains |
website whitelist filter | check if site is allowed | whitelisted domains |
When not to use a HashSet
End of Free Content Preview. Please Sign in or Sign up to buy premium content.