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 again, it won't have any effect since duplicates aren't permitted, as shown in the example.
