Java Programming Language: HashSets

Jesse L
3 min readApr 12, 2022

Hi everyone, welcome back. In this tutorial, we will be going over HashSets in Java. HashSets can be used to store a collection of data similar to an ArrayList, but the key difference is that each of the elements in a HashSet are unique. In other words, there are no duplicate values in a HashSet, making it a great option when wanting to avoid duplicate values. With this introduction out of the way, let’s get into it.

Creating a HashSet

Let’s start by creating a HashSet. Before we can create the HashSet, we need to make sure that we have our HashSet import, which is included within the java.util package:

import java.util.HashSet;

Now, we can successfully create our HashSet:

HashSet<Integer> myHashSet = new HashSet<Integer>();

So now, we have created a HashSet variable. Our HashSet is of the ‘Integer’ data type. When we create our HashSet, we need to specify the data type. We can use other data types as well, such as the ‘String’ data type.

Adding Elements Into the HashSet

Now, let’s try to add elements into our HashSet. We can do this by using the built in add() function that is provided. Let’s see an example:

HashSet<Integer> myHashSet = new HashSet<Integer>();
myHashSet.add(34);
myHashSet.add(891);
myHashSet.add(71);
System.out.println(myHashSet);
Output:
[34, 71, 891]

In the example above, we can see that we added a few integers into our HashSet by using the add() function. We can verify that they were successfully added by printing our HashSet and checking the output.

Let’s try to add in a duplicate value and see what happens:

HashSet<Integer> myHashSet = new HashSet<Integer>();
myHashSet.add(34);
myHashSet.add(891);
myHashSet.add(71);
myHashSet.add(71);
System.out.println(myHashSet);
Output:
[34, 71, 891]

As we can see in the example above, we tried to add ‘71’ twice, but it only appears once in the output. This is due to the fact that each element in the HashSet must be unique.

Removing an Element in a HashSet

--

--

Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.