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,

package com.thispointer.java.collections.hashsets;

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
		setOfInts.add(12);
		setOfInts.add(16);
		setOfInts.add(78);
		setOfInts.add(45);
		
		//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
		System.out.println(setOfInts);
		

	}

}

Output:

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