Java HashSet Tutorial with Examples

HashSet is a part of the Java Collections Framework and provides a collection that uses a hash table for storage. It allows for fast insertion, deletion, and lookup of elements. This tutorial will cover all methods of HashSet with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. HashSet Methods
    • add()
    • addAll()
    • remove()
    • clear()
    • size()
    • isEmpty()
    • contains()
    • iterator()
    • toArray()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

A HashSet in Java is part of the java.util package and implements the Set interface. It uses a hash table for storage, which allows for fast access to its elements. Unlike lists, sets do not allow duplicate elements.

2. Key Points

  • HashSet does not allow duplicate elements.
  • It provides constant-time performance for basic operations like add, remove, and contains.
  • It makes no guarantees regarding the iteration order of the set.
  • HashSet is not synchronized, but it can be synchronized externally.

3. HashSet Methods

3.1. add()

The add() method is used to insert elements into the HashSet.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        names.add("Priya");
        System.out.println(names);
    }
}

Output:

[Rahul, Anjali, Priya]

3.2. addAll()

The addAll() method adds all elements of a collection to the HashSet.

Example:

import java.util.HashSet;
import java.util.Arrays;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.addAll(Arrays.asList("Anjali", "Priya"));
        System.out.println(names);
    }
}

Output:

[Rahul, Anjali, Priya]

3.3. remove()

The remove() method removes the specified element from the HashSet.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        names.add("Priya");
        names.remove("Anjali");
        System.out.println(names);
    }
}

Output:

[Rahul, Priya]

3.4. clear()

The clear() method removes all elements from the HashSet.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        names.add("Priya");
        names.clear();
        System.out.println(names);
    }
}

Output:

[]

3.5. size()

The size() method returns the number of elements in the HashSet.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        names.add("Priya");
        System.out.println(names.size()); // 3
    }
}

Output:

3

3.6. isEmpty()

The isEmpty() method checks if the HashSet is empty.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        System.out.println(names.isEmpty()); // true
        names.add("Rahul");
        System.out.println(names.isEmpty()); // false
    }
}

Output:

true
false

3.7. contains()

The contains() method checks if the HashSet contains a specified element.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        System.out.println(names.contains("Anjali")); // true
        System.out.println(names.contains("Priya")); // false
    }
}

Output:

true
false

3.8. iterator()

The iterator() method returns an iterator for the elements in the HashSet.

Example:

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

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        names.add("Priya");
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output:

Rahul
Anjali
Priya

3.9. toArray()

The toArray() method converts the HashSet into an array.

Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Rahul");
        names.add("Anjali");
        names.add("Priya");
        String[] namesArray = names.toArray(new String[0]);
        for (String name : namesArray) {
            System.out.println(name);
        }
    }
}

Output:

Rahul
Anjali
Priya

4. Use Cases

  • Unique collections: HashSet is used when you need a collection of unique elements.
  • Fast lookups: It provides fast access to elements for lookups, insertions, and deletions.

5. Best Practices

  • Use generics: Always use generics to ensure type safety.
  • Avoid duplicates: Use HashSet to eliminate duplicates from a collection.
  • Choose based on use case: Prefer HashSet when you need a collection with unique elements and do not care about the order of elements.

6. Performance Considerations

  • Time complexity: Basic operations like add, remove, and contains have a constant-time performance on average.
  • Memory usage: Each element in a HashSet requires additional memory for storing hash codes and other data.
  • Iteration order: HashSet makes no guarantees regarding the iteration order of the set.

7. Real-time Example with CRUD Operations

Managing a Student Registration System:

Student.java:

public class Student {
    private String name;
    private int rollNumber;

    public Student(String name, int rollNumber) {
        this.name = name;
        this.rollNumber = rollNumber;
    }

    public String getName() {
        return name;
    }

    public int getRollNumber() {
        return rollNumber;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', rollNumber=" + rollNumber + "}";
    }

    @Override
    public int hashCode() {
        return rollNumber;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Student student = (Student) obj;
        return rollNumber == student.rollNumber;
    }
}

Main.java:

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

public class Main {
    public static void main(String[] args) {
        HashSet<Student> students = new HashSet<>();

        // Create
        students.add(new Student("Rahul", 1));
        students.add(new Student("Anjali", 2));
        students.add(new Student("Priya", 3));

        // Read
        for (Student student : students) {
            System.out.println(student);
        }

        // Update
        students.remove(new Student("Anjali", 2));
        students.add(new Student("Anjali", 22));
        System.out.println("After Update:");
        for (Student student : students) {
            System.out.println(student);
        }

        // Delete
        students.remove(new Student("Rahul", 1));
        System.out.println("After Deletion:");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

Output:

Student{name='Rahul', rollNumber=1}
Student{name='Anjali', rollNumber=2}
Student{name='Priya', rollNumber=3}
After Update:
Student{name='Anjali', rollNumber=22}
Student{name='Priya', rollNumber=3}
Student{name='Rahul', rollNumber=1}
After Deletion:
Student{name='Anjali', rollNumber=22}
Student{name='Priya', rollNumber=3}

8. Conclusion

The HashSet class in Java is a powerful class for managing collections of unique elements. By understanding its methods, use cases, and best practices, you can effectively utilize HashSet in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments