Welcome to this lesson on Java's HashSet. We'll delve into HashSet as if it were a unique collection of space artifacts where duplicates aren't allowed! By the end, you’ll understand how to work with HashSet, and you'll know when to use them instead of other structures like arrays and ArrayLists.
HashSet, which is a part of Java's Collection framework, behaves like a set of unique elements. However, underneath the surface, its mechanism resembles that of HashMap's. Just like a locker in a spaceship that houses only exclusive components, a HashSet only stores unique elements.
Constructing and adding the names of space rocks to our HashSet is a straightforward process, thanks to the new HashSet<>() and add() methods:
The first three lines add three different strings to the HashSet. If we attempt to add "Meteor" again, it won't have any effect since duplicates aren't permitted, as shown in the example.
HashSet doesn't allow direct access to elements by index or whatsoever. However, we can search for a specific element using the contains() method:
isCometPresent will be true as "Comet" is a part of the hash set we created earlier. You can remove an element through remove() and use isEmpty() and size() methods to inspect the state of the HashSet.
Here is an example:
After the above operations, "Comet" is removed from the HashSet, isEmpty is false since there are still elements left, and size reflects the number of elements in the HashSet.
