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:

HashSet<String> spaceObjects = new HashSet<>();
spaceObjects.add("Asteroid");
spaceObjects.add("Meteor");
spaceObjects.add("Comet");
System.out.println(spaceObjects); // Output: [Asteroid, Comet, Meteor]

spaceObjects.add("Meteor"); // adding a duplicate element
System.out.println(spaceObjects); // Output: [Asteroid, Comet, Meteor]
// The duplicate element wasn't added

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.

Accessing and Inspecting HashSet Elements

HashSet doesn't allow direct access to elements by index or whatsoever. However, we can search for a specific element using the contains() method:

boolean isCometPresent = spaceObjects.contains("Comet");
System.out.println("Is Comet present in the set? " + isCometPresent); // Output: "Is Comet present in the set? true"

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:

HashSet<String> spaceObjects = new HashSet<>();
spaceObjects.add("Asteroid");
spaceObjects.add("Meteor");
spaceObjects.add("Comet");

System.out.println("Is Comet present in the set? " + spaceObjects.contains("Comet"));
// Output: "Is Comet present in the set? true"
spaceObjects.remove("Comet");
System.out.println("Is Comet present in the set? " + spaceObjects.contains("Comet"));
// Output: "Is Comet present in the set? false"

System.out.println("Is set empty? " + spaceObjects.isEmpty()); // Output: "Is set empty? false"
System.out.println(spaceObjects.size()); // Output: 2            

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.

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