HashSet in Java

Java HashSet: A Complete Guide with Examples and Exercises

In Java, the HashSet class is part of the java.util package and implements the Set interface. It is a collection of unique elements and does not allow duplicate values. A HashSet is backed by a hash table, which provides constant-time performance (O(1)) for basic operations like add, remove, and contains, assuming the hash function distributes the elements properly.

This guide explores the key concepts of HashSet, demonstrates its usage with examples, and includes exercises to help you understand how to work with this collection.


Table of Contents

  1. Introduction to HashSet
  2. Creating a HashSet
  3. Basic HashSet Operations
  • Adding Elements
  • Removing Elements
  • Checking for Presence of an Element
  1. Iterating Over a HashSet
  2. HashSet vs HashMap
  3. Common HashSet Methods
  4. Exercise
  5. Conclusion

1. Introduction to HashSet

A HashSet is a collection that implements the Set interface. As a Set, it does not allow duplicate elements. The main advantages of using a HashSet are:

  • No Duplicates: Automatically eliminates duplicates and ensures that every element is unique.
  • Unordered: The order of elements in a HashSet is not guaranteed. Unlike a List, it doesn’t maintain the order in which elements were added.
  • Fast Operations: The HashSet is backed by a hash table, providing efficient performance for adding, removing, and checking for the presence of elements.

Key Characteristics of HashSet:

  • No duplicate elements.
  • Unordered collection.
  • Allows null elements (only one null element can be stored).
  • Not synchronized (not thread-safe).

2. Creating a HashSet

You can create a HashSet using its constructor. If no initial capacity is specified, the default capacity is used. You can also provide an initial capacity and load factor to optimize performance if necessary.

Example 1: Creating an Empty HashSet

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        // Creating an empty HashSet
        HashSet<String> set = new HashSet<>();

        // Adding elements
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");

        // Printing the HashSet
        System.out.println("HashSet: " + set);
    }
}

Output:

HashSet: [Apple, Banana, Orange]

Note that the order of the elements might vary every time you run the program because the elements are stored in an unordered fashion.

Example 2: Creating a HashSet with Initial Capacity

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        // Creating a HashSet with an initial capacity of 10 and load factor 0.75
        HashSet<Integer> set = new HashSet<>(10, 0.75f);

        // Adding elements
        set.add(10);
        set.add(20);
        set.add(30);

        // Printing the HashSet
        System.out.println("HashSet: " + set);
    }
}

3. Basic HashSet Operations

Adding Elements

You can add elements to a HashSet using the add() method. If the element is already present, the add() method will return false and will not add the duplicate element.

Example: Adding Elements

import java.util.HashSet;

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

        // Adding a duplicate element
        boolean isAdded = set.add("Apple");

        System.out.println("Element 'Apple' added: " + isAdded);
        System.out.println("HashSet: " + set);
    }
}

Output:

Element 'Apple' added: false
HashSet: [Apple, Banana, Orange]

Removing Elements

To remove an element from the HashSet, you can use the remove() method. This method returns true if the element was successfully removed and false if the element was not present.

Example: Removing Elements

import java.util.HashSet;

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

        // Removing an element
        boolean isRemoved = set.remove("Banana");

        System.out.println("Element 'Banana' removed: " + isRemoved);
        System.out.println("HashSet: " + set);
    }
}

Output:

Element 'Banana' removed: true
HashSet: [Apple, Orange]

Checking for Presence of an Element

To check if an element is present in the HashSet, use the contains() method. It returns true if the element exists, otherwise false.

Example: Checking for Presence

import java.util.HashSet;

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

        // Checking if an element is present
        System.out.println("Contains 'Banana': " + set.contains("Banana"));
        System.out.println("Contains 'Grapes': " + set.contains("Grapes"));
    }
}

Output:

Contains 'Banana': true
Contains 'Grapes': false

4. Iterating Over a HashSet

You can iterate over the elements in a HashSet using an iterator or an enhanced for loop. The order of iteration is not guaranteed.

Example 1: Using Enhanced for Loop

import java.util.HashSet;

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

        // Iterating using enhanced for loop
        for (String fruit : set) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Orange

Example 2: Using Iterator

import java.util.HashSet;
import java.util.Iterator;

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

        // Iterating using Iterator
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

5. HashSet vs HashMap

Although both HashSet and HashMap are based on a hash table, there are key differences:

FeatureHashSetHashMap
Element StructureStores only elements (unique)Stores key-value pairs (unique keys)
Null ElementsAllows one null elementAllows one null key and multiple null values
PerformanceO(1) for add, remove, containsO(1) for get, put, remove, contains

6. Common HashSet Methods

  • add(E e): Adds the specified element to the set if it is not already present.
  • remove(Object o): Removes the specified element from the set.
  • contains(Object o): Returns true if the set contains the specified element.
  • size(): Returns the number of elements in the set.
  • clear(): Removes all elements from the set.
  • isEmpty(): Returns true if the set contains no elements.

7. Exercise

Exercise 1: Create a HashSet of Names

  1. Create a HashSet to store a list of names.
  2. Add five names to the set.
  3. Remove a name from the set.
  4. Check if a particular name is in the set.

Exercise 2: Unique Numbers in a List

  1. Create a HashSet and add a list of numbers (with duplicates) to it.
  2. Print the set to verify that only unique numbers are retained.

Solution for Exercise 1:

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("David");
        names.add("Eve");

        // Removing a name
        names.remove("David");

        // Checking if a name exists
        System.out.println("Contains 'Alice': " + names.contains("Alice"));
        System.out.println("Contains 'David': " + names.contains("David"));

        // Printing the final set
        System.out.println("Names: " + names);
    }
}

Conclusion

The HashSet is a powerful collection class in Java, ideal for storing unique

elements with constant-time operations. Its unordered nature makes it suitable for various use cases, such as eliminating duplicates from a list or checking membership quickly. By mastering HashSet, you can efficiently manage sets of data in your Java applications.

Leave a Comment

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

Scroll to Top