VOOZH about

URL: https://www.geeksforgeeks.org/java/initializing-hashset-java/

⇱ Initializing HashSet in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Initializing HashSet in Java

Last Updated : 22 Jan, 2026

In Java, HashSet is a part of the java.util package is used to store a collection of unique elements. It does not allow duplicate values and does not maintain any insertion order. Initializing a HashSet can be done in multiple ways depending on the use case.

Method 1: Using a Constructor

In this approach, an array is converted to a list and passed to the HashSet constructor that accepts a collection.

Note: HashSet does not guarantee sorted order; the output order may vary.


Output
[1, 2, 3, 4, 5, 6, 7, 8]

Explanation:

  • Integer[] arr defines an array that contains duplicate elements (3 appears twice).
  • Arrays.asList(arr) converts the array into a List.
  • new HashSet<>(...) creates a HashSet using that list.
  • While adding elements, HashSet automatically removes duplicates.
  • The order of output is not guaranteed because HashSet is unordered.

Method 2: using Collections

Collections class consists of several methods that operate on collections. 

a) Collection.addAll()

Adds all elements to the specified collection.


Output
[1, 2, 3, 4, 5, 6, 7, 8]

Explanation:

  • An empty HashSet is created using new HashSet<>().
  • Collections.addAll(set, arr) adds all elements from the array to the set.
  • Duplicate values are ignored automatically by the Set.
  • This approach is useful when you already have an empty collection and want to populate it in one statement.

b) Using Collections.unmodifiableSet()

Creates an unmodifiable (read-only) view of the set.


Output
[1, 2, 3, 4, 5, 6, 7, 8]

Explanation:

  • A HashSet is first created from the array using the constructor approach.
  • Collections.unmodifiableSet() wraps the set and returns a read-only view.
  • Any attempt to modify the set (e.g., add(), remove()) will throw an UnsupportedOperationException.
  • This is useful when you want to protect the data from modification.

Method 3: using .add() each Method 

Create a set and using .add() method we add the elements into the set 


Output
[1, 2, 3, 4, 5, 6, 7, 8]

Note: The order of elements in the output may vary because HashSet does not maintain insertion or sorted order.

Explanation:

  • An empty HashSet is created.
  • Elements are added one by one using add().
  • When set.add(3) is called the second time, it is ignored because Set does not allow duplicates.
  • This approach is useful when elements are added dynamically at runtime.
Comment