HashSet ใช้ Hashing เพื่อจัดการข้อมูล เรามาดูตัวอย่างกัน −
ตัวอย่าง
import java.util.*;
public class Demo{
private final String f_str, l_str;
public Demo(String f_str, String l_str){
this.f_str = f_str;
this.l_str = l_str;
}
public boolean equals(Object o){
if (o instanceof Demo)
return true;
Demo n = (Demo)o;
return n.f_str.equals(f_str) && n.l_str.equals(l_str);
}
public static void main(String[] args){
Set<Demo> my_set = new HashSet<Demo>();
my_set.add(new Demo("Joe", "Goldberg"));
System.out.println("Added a new element to the set");
System.out.println("Does the set contain a new instance of the object? ");
System.out.println(my_set.contains(new Demo("Jo", "Gold")));
}
} ผลลัพธ์
Added a new element to the set Does the set contain a new instance of the object? false
คลาส 'Demo' ประกอบด้วยสตริงสุดท้ายและตัวสร้าง มีการกำหนดฟังก์ชันเท่ากับที่ตรวจสอบว่าอ็อบเจ็กต์เป็นอินสแตนซ์ของคลาสเฉพาะหรือไม่ คืนค่า จริง หากเป็นอินสแตนซ์ที่ส่งอ็อบเจ็กต์ไปยังคลาส และตรวจสอบโดยใช้ฟังก์ชัน 'equals' ในฟังก์ชันหลัก ชุดใหม่จะถูกสร้างขึ้นและอินสแตนซ์จะถูกสร้างขึ้น มีการตรวจสอบโดยใช้ตัวดำเนินการ 'instanceof'