Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

The HashSet ใน Java - HashSet Class คู่มือครบถ้วน

HashSet Extends AbstractSet Implements Set Interface สร้าง Collection ที่ใช้ Hash Table สำหรับ Storage

Hashing: ใช้ Informational Content ของ Key กำหนด Unique Value เรียกว่า Hash Code Hash Code ใช้เป็น Index จัดเก็บ Data ที่ Link กับ Key การแปลง Key เป็น Hash Code เกิดขึ้นอัตโนมัติ

ตัวอย่างที่ 1: HashSet Basic Operations

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<String>();
        hashSet.add("One");
        hashSet.add("Two");
        hashSet.add("Three");
        hashSet.add("Four");
        hashSet.add("Five");
        hashSet.add("Six");
        System.out.println("Hash set values = " + hashSet);
    }
}

ผลลัพธ์

Hash set values = [Five, Six, One, Four, Two, Three]

สังเกต: ลำดับไม่คงที่ (Hash-based) และไม่มี Duplicate

ตัวอย่างที่ 2: Remove Element จาก HashSet

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        HashSet<String> newset = new HashSet<String>();
        newset.add("Learning");
        newset.add("Easy");
        newset.add("Simply");
        
        System.out.println("Values before remove: " + newset);
        boolean isRemoved = newset.remove("Easy");
        System.out.println("Return value after remove: " + isRemoved);
        System.out.println("Values after remove: " + newset);
    }
}

ผลลัพธ์

Values before remove: [Learning, Easy, Simply]
Return value after remove: true
Values after remove: [Learning, Simply]

คุณสมบัติสำคัญของ HashSet

  • ไม่รับ Duplicate Elements
  • อนุญาต Null Element ได้ 1 ตัว
  • ไม่保证 Order (ใช้ LinkedHashSet หากต้องการ Insertion Order)
  • ไม่ Thread-Safe (ใช้ Collections.synchronizedSet() หรือ ConcurrentHashMap.newKeySet())
  • Time Complexity: O(1) สำหรับ add, remove, contains (Average Case)