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

การทำงานภายในของ HashMap ใน Java

เมธอด hashCode() ใช้ดึง hash code ของ object ใน Java เป็นเมธอดของ super class Object คืนค่า memory reference ของ object เป็น integer เป็น native method ไม่มีวิธีโดยตรงใน Java ดึง reference ของ object

เพื่อ performance ของ HashMap ควรใช้ hashCode() ให้ถูกต้อง เมธอดนี้คำนวณ bucket และ index values กำหนดดังนี้:

public native int hashCode()

Bucket คืออะไร? เป็น element ที่เก็บ nodes สามารถมีมากกว่า 2 nodes ใน bucket เดียว nodes เชื่อมต่อกันด้วย linked list ความจุของ hashmap คำนวณจาก bucket และ load factor:

Capacity = number of buckets * load factor

เมธอด equals() ตรวจสอบความเท่ากันระหว่างสอง object ก็มาจาก super class Object สามารถ override ใน custom class ได้ คืน true/false ขึ้นอยู่กับความเท่ากัน

Index value สร้างขึ้นเพื่อไม่ให้ array ใหญ่เกินไป (หลีกเลี่ยง OutOfMemoryException) สูตรหา index:

Index = hashCode(key) & (n-1)  // n = number of buckets

ตัวอย่าง

import java.util.HashMap;

class hash_map {
    String key;
    hash_map(String key) {
        this.key = key;
    }
    @Override
    public int hashCode() {
        int hash = (int)key.charAt(0);
        System.out.println("The hash code for key : " + key + " = " + hash);
        return hash;
    }
    @Override
    public boolean equals(Object obj) {
        return key.equals(((hash_map)obj).key);
    }
}

public class Demo {
    public static void main(String[] args) {
        HashMap my_map = new HashMap();
        my_map.put(new hash_map("This"), 15);
        my_map.put(new hash_map("is"), 35);
        my_map.put(new hash_map("a"), 26);
        my_map.put(new hash_map("sample"), 45);
        System.out.println("The value for key 'this' is : " + my_map.get(new hash_map("This")));
        System.out.println("The value for key 'is' is: " + my_map.get(new hash_map("is")));
        System.out.println("The value for key 'a' is: " + my_map.get(new hash_map("a")));
        System.out.println("The value for key 'sample' is: " + my_map.get(new hash_map("sample")));
    }
}

ผลลัพธ์

The hash code for key : This = 84
The hash code for key : is = 105
The hash code for key : a = 97
The hash code for key : sample = 115
The hash code for key : This = 84
The value for key 'this' is : 15
The hash code for key : is = 105
The value for key 'is' is: 35
The hash code for key : a = 97
The value for key 'a' is: 26
The hash code for key : sample = 115
The value for key 'sample' is: 45

คลาส hash_map กำหนด string key และ constructor override hashCode() ใช้ char แรกของ key เป็น hash code override equals() เปรียบเทียบ key คลาส Demo สร้าง HashMap put ข้อมูลด้วย hash_map object แล้ว get ค่ากลับมา