Introducing Java's HashSet

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.

Constructing a HashSet

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal