Java WeakHashMap

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về Java WeakHashMap và các hoạt động của nó với sự trợ giúp của các ví dụ. Chúng ta cũng sẽ tìm hiểu về sự khác biệt giữa WeakHashMap và HashMap

Các WeakHashMaplớp học của khuôn khổ bộ sưu tập Java cung cấp các tính năng của cấu trúc dữ liệu bảng băm ..

Nó thực hiện giao diện Bản đồ .

Lưu ý : Các khóa của bản đồ băm yếu thuộc loại WeakReference .

Đối tượng của kiểu tham chiếu yếu có thể được thu gom rác trong Java nếu tham chiếu không còn được sử dụng trong chương trình.

Trước tiên, chúng ta hãy học cách tạo một bản đồ băm yếu. Sau đó, chúng ta sẽ tìm hiểu nó khác với bản đồ băm như thế nào.

Tạo một WeakHashMap

Để tạo một bản đồ băm yếu, java.util.WeakHashMaptrước tiên chúng ta phải nhập gói. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo các bản đồ băm yếu trong Java.

//WeakHashMap creation with capacity 8 and load factor 0.6
WeakHashMap<Key, Value> numbers = new WeakHashMap<>(8, 0.6);

Trong đoạn mã trên, chúng tôi đã tạo một bản đồ băm yếu có tên là các số .

Đây,

  • Key – a unique identifier used to associate each element (value) in a map
  • Value – elements associated by keys in a map

Chú ý phần new WeakHashMap<>(8, 0.6). Ở đây, tham số đầu tiên là dung lượng và tham số thứ hai là loadFactor .

  • capacity – The capacity of this map is 8. Meaning, it can store 8 entries.
  • loadFactor – The load factor of this map is 0.6. This means whenever our hash table is filled by 60%, the entries are moved to a new hash table of double the size of the original hash table.

Công suất mặc định và hệ số tải

Có thể tạo một bản đồ băm yếu mà không cần xác định dung lượng và hệ số tải của nó. Ví dụ,

// WeakHashMap with default capacity and load factor
WeakHashMap<Key, Value> numbers1 = new WeakHashMap<>();

Theo mặc định,

  • the capacity of the map will be 16
  • the load factor will be 0.75

Sự khác biệt giữa HashMap và WeakHashMap

Hãy để chúng tôi xem việc triển khai một bản đồ băm yếu trong Java.

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        // Creating WeakHashMap of numbers
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

        String two = new String("Two");
        Integer twoValue = 2;
        String four = new String("Four");
        Integer fourValue = 4;

        // Inserting elements
        numbers.put(two, twoValue);
        numbers.put(four, fourValue);
        System.out.println("WeakHashMap: " + numbers);

        // Make the reference null
        two = null;

        // Perform garbage collection
        System.gc();

        System.out.println("WeakHashMap after garbage collection: " + numbers);
    }
}

Đầu ra

WeakHashMap: {Four=4, Two=2}
WeakHashMap after garbage collection: {Four}

Như chúng ta có thể thấy, khi khóa hai của một bản đồ băm yếu được đặt thành nullvà thực hiện thu gom rác, khóa sẽ bị xóa.

Đó là bởi vì không giống như các bản đồ băm, các khóa của các bản đồ băm yếu thuộc loại tham chiếu yếu . Điều này có nghĩa là mục nhập bản đồ sẽ bị bộ thu gom rác loại bỏ nếu khóa của mục nhập đó không còn được sử dụng. Điều này rất hữu ích để tiết kiệm tài nguyên.

Bây giờ chúng ta hãy xem cách triển khai tương tự trong một bản đồ băm.

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Creating HashMap of even numbers
        HashMap<String, Integer> numbers = new HashMap<>();

        String two = new String("Two");
        Integer twoValue = 2;
        String four = new String("Four");
        Integer fourValue = 4;

        // Inserting elements
        numbers.put(two, twoValue);
        numbers.put(four, fourValue);
        System.out.println("HashMap: " + numbers);

        // Make the reference null
        two = null;

        // Perform garbage collection
        System.gc();

        System.out.println("HashMap after garbage collection: " + numbers);
    }
}

Đầu ra

HashMap: {Four=4, Two=2}
HashMap after garbage collection: {Four=4, Two=2}

Ở đây, khi khóa hai của bản đồ băm được đặt thành nullvà thực hiện thu gom rác, khóa sẽ không bị xóa.

Điều này là do không giống như các khóa bản đồ băm yếu của bản đồ băm thuộc loại tham chiếu mạnh . Điều này có nghĩa là mục nhập bản đồ không bị bộ thu gom rác loại bỏ mặc dù khóa của mục nhập đó không còn được sử dụng.

Lưu ý : Tất cả các chức năng của bản đồ băm và bản đồ băm yếu đều tương tự nhau, ngoại trừ các khóa của bản đồ băm yếu là tham chiếu yếu, trong khi các khóa của bản đồ băm có tham chiếu mạnh.

Tạo WeakHashMap từ các Bản đồ khác

Đây là cách chúng ta có thể tạo một bản đồ băm yếu từ các bản đồ khác.

import java.util.HashMap;
import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        // Creating a hashmap of even numbers
        HashMap<String, Integer> evenNumbers = new HashMap<>();

        String two = new String("Two");
        Integer twoValue = 2;
        evenNumbers.put(two, twoValue);
        System.out.println("HashMap: " + evenNumbers);

        // Creating a weak hash map from other hashmap
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>(evenNumbers);

        System.out.println("WeakHashMap: " + numbers);
    }
}

Đầu ra

HashMap: {Two=2}
WeakHashMap: {Two=2}

Phương thức của WeakHashMap

Các WeakHashMaplớp học cung cấp phương pháp đó cho phép chúng tôi thực hiện các hoạt động khác nhau trên bản đồ.

Chèn các phần tử vào WeakHashMap

  • put() – inserts the specified key/value mapping to the map
  • putAll() – inserts all the entries from specified map to this map
  • putIfAbsent() – inserts the specified key/value mapping to the map if the specified key is not present in the map

Ví dụ,

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        // Creating WeakHashMap of even numbers
        WeakHashMap<String, Integer> evenNumbers = new WeakHashMap<>();

        String two = new String("Two");
        Integer twoValue = 2;

        // Using put()
        evenNumbers.put(two, twoValue);

        String four = new String("Four");
        Integer fourValue = 4;

        // Using putIfAbsent()
        evenNumbers.putIfAbsent(four, fourValue);
        System.out.println("WeakHashMap of even numbers: " + evenNumbers);

        //Creating WeakHashMap of numbers
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

        String one = new String("One");
        Integer oneValue = 1;
        numbers.put(one, oneValue);

        // Using putAll()
        numbers.putAll(evenNumbers);
        System.out.println("WeakHashMap of numbers: " + numbers);
    }
}

Đầu ra

WeakHashMap of even numbers: {Four=4, Two=2}
WeakHashMap of numbers: {Two=2, Four=4, One=1}

Truy cập các phần tử WeakHashMap

1. Sử dụng entrySet (), keySet () và các giá trị ()

  • entrySet() – returns a set of all the key/value mapping of the map
  • keySet() – returns a set of all the keys of the map
  • values() – returns a set of all the values of the map

Ví dụ,

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        // Creating WeakHashMap of even numbers
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

        String one = new String("One");
        Integer oneValue = 1;
        numbers.put(one, oneValue);

        String two = new String("Two");
        Integer twoValue = 2;
        numbers.put(two, twoValue);

        System.out.println("WeakHashMap: " + numbers);

        // Using entrySet()
        System.out.println("Key/Value mappings: " + numbers.entrySet());

        // Using keySet()
        System.out.println("Keys: " + numbers.keySet());

        // Using values()
        System.out.println("Values: " + numbers.values());
    }
}

Đầu ra

WeakHashMap: {Two=2, One=1}
Key/Value mappings: [Two=2, One=1]
Keys: [Two, One]
Values: [1, 2]

2. Sử dụng get () và getOrDefault ()

  • get() – Returns the value associated with the specified key. Returns null if the key is not found.
  • getOrDefault() – Returns the value associated with the specified key. Returns the specified default value if the key is not found.

Ví dụ,

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        // Creating WeakHashMap of even numbers
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

        String one = new String("One");
        Integer oneValue = 1;
        numbers.put(one, oneValue);

        String two = new String("Two");
        Integer twoValue = 2;
        numbers.put(two, twoValue);

        System.out.println("WeakHashMap: " + numbers);

        // Using get()
        int value1 = numbers.get("Two");
        System.out.println("Using get(): " + value1);

        // Using getOrDefault()
        int value2 = numbers.getOrDefault("Four", 4);
        System.out.println("Using getOrDefault(): " + value2);

    }
}

Đầu ra

WeakHashMap: {Two=2, One=1}
Using get(): 2
Using getOrDefault(): 4

Xóa các phần tử WeakHashMap

  • remove(key) – returns and removes the entry associated with the specified key from the map
  • remove(key, value) – removes the entry from the map only if the specified key mapped to the specified value and return a boolean value

Ví dụ,

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        // Creating WeakHashMap of even numbers
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

        String one = new String("One");
        Integer oneValue = 1;
        numbers.put(one, oneValue);

        String two = new String("Two");
        Integer twoValue = 2;
        numbers.put(two, twoValue);

        System.out.println("WeakHashMap: " + numbers);

        // Using remove() with single parameter
        int value = numbers.remove("Two");
        System.out.println("Removed value: " + value);

        // Using remove() with 2 parameters
        boolean result = numbers.remove("One", 3);
        System.out.println("Is the entry {One=3} removed? " + result);

        System.out.println("Updated WeakHashMap: " + numbers);
    }
}

Đầu ra

WeakHashMap: {Two=2, One=1}
Removed value: 2
Is the entry {One=3} removed? False
Updated WeakHashMap: {One=1}

Các phương pháp khác của WeakHashMap

MethodDecfscription
clear()Removes all the entries from the map
containsKey()Checks if the map contains the specified key and returns a boolean value
containsValue()Checks if the map contains the specified value and returns a boolean value
size()Returns the size of the map
isEmpty()Checks if the map is empty and returns a boolean value

Để tìm hiểu thêm, hãy truy cập Java WeakHashMap (tài liệu Java chính thức) .









Gõ tìm kiếm nhanh...