0
0
JavaHow-ToBeginner · 3 min read

How to Create HashSet in Java: Syntax and Examples

To create a HashSet in Java, import java.util.HashSet and instantiate it using new HashSet<>(). This creates a collection that stores unique elements without any order.
📐

Syntax

The basic syntax to create a HashSet is:

  • HashSet<Type> setName = new HashSet<>();
  • Type is the type of elements you want to store (e.g., String, Integer).
  • This creates an empty HashSet that you can add unique elements to.
java
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
    }
}
💻

Example

This example shows how to create a HashSet, add elements, and print them. Notice that duplicates are ignored and order is not guaranteed.

java
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple"); // duplicate
        fruits.add("Orange");

        System.out.println("Fruits in the set:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
Output
Fruits in the set: Apple Banana Orange
⚠️

Common Pitfalls

Common mistakes when creating or using a HashSet include:

  • Forgetting to import java.util.HashSet.
  • Expecting the elements to keep the order they were added (HashSet does not maintain order).
  • Adding duplicate elements thinking they will be stored multiple times (duplicates are ignored).
  • Using mutable objects as elements without proper hashCode() and equals() methods, which can cause unexpected behavior.
java
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        // Wrong: No import statement (will cause compile error)
        // HashSet<String> set = new HashSet<>();

        // Right:
        HashSet<String> set = new HashSet<>();
        set.add("Hello");
        set.add("Hello"); // duplicate ignored

        System.out.println(set); // Prints [Hello]
    }
}
Output
[Hello]
📊

Quick Reference

Here is a quick summary of HashSet creation and usage:

ActionCode ExampleNotes
Create empty HashSetHashSet<String> set = new HashSet<>();Stores unique elements, no order
Add elementset.add("Element");Adds if not already present
Check if containsset.contains("Element");Returns true or false
Remove elementset.remove("Element");Removes element if present
Iterate elementsfor(String e : set) { ... }Order is unpredictable

Key Takeaways

Use new HashSet<>() to create a HashSet that stores unique elements.
HashSet does not keep elements in the order they were added.
Duplicates are automatically ignored when adding elements.
Always import java.util.HashSet before using it.
Mutable objects in HashSet need proper hashCode() and equals() methods.