HashSet ขยาย AbstractSet และใช้อินเทอร์เฟซ Set มันสร้างคอลเลกชันที่ใช้ตารางแฮชสำหรับการจัดเก็บ
ตารางแฮชเก็บข้อมูลโดยใช้กลไกที่เรียกว่าการแฮช ในการแฮช เนื้อหาที่เป็นข้อมูลของคีย์ใช้เพื่อกำหนดค่าที่ไม่ซ้ำกัน ซึ่งเรียกว่าโค้ดแฮช
รหัสแฮชจะใช้เป็นดัชนีที่เก็บข้อมูลที่เกี่ยวข้องกับคีย์ การแปลงคีย์เป็นรหัสแฮชจะดำเนินการโดยอัตโนมัติ
ตัวอย่าง
ให้เรามาดูตัวอย่างการใช้ HashSet ใน Java −
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]
ตัวอย่าง
ให้เราดูตัวอย่างอื่นเพื่อลบองค์ประกอบออกจาก 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]