How to create and add elements in a HashSet in Java

+In this article we will discuss how to create a HashSet of integers and add elements in it.

Creating a HashSet Object for integer

// Create a HashSet of int
HashSet<Integer> setOfInts = new HashSet<>();

This hashset object can contain only unique integers.

Adding Element in a HashSet

To add an element in a HashSet we will use its following member function,

public boolean add(E e)

This add() function will try to add element in HashSet and if element already exists in HashSet then it will return false;

Checkout the following example,


import java.util.HashSet;

public class Example0 {

	public static void main(String[] args) {
		// Create a HashSet of integers
		HashSet<Integer> setOfInts = new HashSet<>();
		//Add numbers to HashSet
		//Try to Add a duplicate element
		boolean ret = setOfInts.add(12);
		if(ret == false)
			System.out.println("Failed to add duplicate element");
		// Print the HashSet




Failed to add duplicate element
[16, 12, 45, 78]

[showads ad=inside_post]


In the previous example, when we tried ┬áto add “12” again into the HashSet then add(0 function returned false. This is because HashSet only contains unique elements.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top