Feedback Form

Java HashSet: Unordered Unique Collection Mastery

Java HashSet: Unordered Unique Collection Mastery

Introduction to HashSet in Java

अगर आप Java Programming सीख रहे हैं तो HashSet एक बहुत ही जरूरी Collection Class है। यह Set Interface का हिस्सा है और इसका मुख्य काम है — unique elements को store करना। इसका मतलब यह duplicate values को allow नहीं करता और elements का कोई fixed order नहीं होता। यानी HashSet में डाटा unordered और unique रहता है।

HashSet का use तब किया जाता है जब हमें fast search, insertion और deletion चाहिए लेकिन order maintain नहीं करना। यह HashMap पर based होता है और internally hashing concept का use करता है।

Key Features of HashSet

  • Duplicate elements को allow नहीं करता।
  • Elements unordered form में store होते हैं।
  • Null element को allow करता है (केवल एक बार)।
  • Fast access और search performance — average time O(1)।
  • Internally HashMap पर based होता है।

HashSet Class Hierarchy

HashSet की hierarchy इस तरह होती है:


java.lang.Object
   ↳ java.util.AbstractCollection
        ↳ java.util.AbstractSet
             ↳ java.util.HashSet

HashSet → AbstractSet → AbstractCollection → Object और यह Set Interface को implement करता है।

Declaration and Syntax

HashSet को declare और initialize करने का basic syntax इस प्रकार होता है:


HashSet<Type> set = new HashSet<>();

Example:


HashSet<String> names = new HashSet<>();
names.add("Amit");
names.add("Rohit");
names.add("Neha");
System.out.println(names);

Output unordered होगा क्योंकि HashSet elements का order maintain नहीं करता।

Internal Working of HashSet

HashSet internally HashMap पर काम करता है। जब हम कोई element add करते हैं, तो HashSet उस value को HashMap के key के रूप में store करता है और dummy value के तौर पर एक constant object रखता है।

जब कोई नया element add किया जाता है, तो उसका hashCode() calculate किया जाता है और उसे particular bucket में रखा जाता है। अगर bucket में पहले से कोई element है, तो equals() method से comparison होता है ताकि duplicate न आए।

Internal Storage Structure

Operation Working
add(E e) Hash code compute करता है और element को HashMap में put करता है।
contains(Object o) Hash code match कर element की presence check करता है।
remove(Object o) Key के आधार पर element delete करता है।

Constructors of HashSet

HashSet class में कई constructors available हैं:

  • HashSet() — Default constructor, 16 capacity और 0.75 load factor के साथ।
  • HashSet(int initialCapacity) — Custom initial capacity सेट करने के लिए।
  • HashSet(int initialCapacity, float loadFactor) — दोनों customize करने के लिए।
  • HashSet(Collection c) — किसी existing collection से HashSet बनाता है।

Common Methods of HashSet

HashSet में कुछ commonly used methods इस प्रकार हैं:

Method Description
add(E e) Element को set में जोड़ता है। अगर duplicate है तो ignore करता है।
remove(Object o) दिए गए element को remove करता है।
contains(Object o) Check करता है कि element मौजूद है या नहीं।
size() Set में कितने elements हैं, ये बताता है।
isEmpty() Check करता है कि set empty है या नहीं।
clear() Set के सारे elements remove करता है।
iterator() Set के elements पर iterate करने के लिए iterator return करता है।

Example Program of HashSet

चलो एक simple example देखते हैं जो HashSet के basic operations को दिखाता है:


import java.util.HashSet;

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

        System.out.println("Fruits Set: " + fruits);
        System.out.println("Contains Mango? " + fruits.contains("Mango"));
        fruits.remove("Banana");
        System.out.println("After Removal: " + fruits);
    }
}

Output में आप देखोगे कि duplicate “Apple” केवल एक बार show होगा।

Iterating HashSet

HashSet को traverse करने के लिए हम Iterator या Enhanced for loop का use कर सकते हैं।


for (String fruit : fruits) {
    System.out.println(fruit);
}

क्योंकि elements unordered होते हैं, हर बार iteration में order change हो सकता है।

Difference Between HashSet and List

Basis HashSet ArrayList
Order Unordered Ordered
Duplicates Not allowed Allowed
Performance Fast for search & delete Slower comparatively
Null Values Only one null allowed Multiple null allowed

HashSet vs LinkedHashSet

LinkedHashSet भी Set Interface को implement करता है लेकिन यह elements के insertion order को maintain करता है।

Feature HashSet LinkedHashSet
Order Unordered Insertion order maintained
Speed Faster (less overhead) Slower (due to linked list)

Use Cases of HashSet

  • Duplicate entries remove करने के लिए।
  • Fast membership check (contains operation)।
  • Unique values store करने वाले programs में।
  • Data cleaning और filtering के लिए।

Limitations of HashSet

  • Elements unordered होते हैं, इसलिए index-based access possible नहीं।
  • Thread-safe नहीं है — multiple threads के साथ synchronized version चाहिए।
  • Load factor बढ़ने पर rehashing costly हो सकती है।

Thread Safety and Synchronization

HashSet by default not synchronized होता है। अगर multi-threaded environment में use करना है, तो इसे synchronized version में convert करना चाहिए:


Set<String> syncSet = Collections.synchronizedSet(new HashSet<>());

Time Complexity of HashSet Operations

Operation Average Case Worst Case
add() O(1) O(n)
remove() O(1) O(n)
contains() O(1) O(n)
iteration() O(n) O(n)

Real-life Examples of HashSet Usage

  • Online exam systems में unique student IDs store करने के लिए।
  • Duplicate-free email list बनाने के लिए।
  • Unique keywords या tags collect करने के लिए।
  • Game development में unique player names या objects रखने के लिए।

Best Practices for Using HashSet

  • अगर order important नहीं है तो HashSet prefer करें।
  • अगर frequent insertion और deletion है तो HashSet ideal choice है।
  • Custom objects के लिए equals() और hashCode() को properly override करें।
  • Null values handle करते समय NullPointerException से बचें।

Using Custom Objects in HashSet

अगर आप custom class के objects store कर रहे हैं तो equals() और hashCode() methods को override करना जरूरी है ताकि duplicate पहचान सके।


class Student {
    int id;
    String name;

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

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

    @Override
    public boolean equals(Object obj) {
        Student s = (Student) obj;
        return this.id == s.id;
    }
}

public class Test {
    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<>();
        set.add(new Student(1, "Amit"));
        set.add(new Student(2, "Ravi"));
        set.add(new Student(1, "Amit"));
        System.out.println(set.size());
    }
}

यहाँ output 2 नहीं बल्कि 2 के बजाय 2 unique IDs होंगे क्योंकि duplicate ID वाले objects ignore हो जाएंगे।

HashSet vs TreeSet

Feature HashSet TreeSet
Order Unordered Sorted (natural order)
Performance O(1) O(log n)
Null Elements Allowed Not allowed

Important Points to Remember

  • HashSet fast है क्योंकि यह hashing का use करता है।
  • Order कभी guarantee नहीं होता।
  • Custom object के लिए hashCode() और equals() override करना जरूरी है।
  • Thread safety के लिए Collections.synchronizedSet() का use करें।