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

ความสำคัญของ HashSet ใน Java

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 my_set = new HashSet();
        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 มี final string และ constructor equals() ตรวจสอบ instanceof คืน true (หมายเหตุ: implementation นี้มี bug ควรเปรียบเทียบ field ด้วย) ใน main สร้าง HashSet เพิ่มอ็อบเจ็กต์ ตรวจสอบ contains ด้วยอ็อบเจ็กต์ใหม่ที่มีค่าต่างกัน คืน false