English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In questo tutorial, esploreremo Java WeakHashMap e le sue operazioni tramite esempi. Inoltre, impareremo la differenza tra WeakHashMap e HashMap
Java集合框架的WeakHashMap类提供了哈希表数据结构的功能。
它实现了Map接口。
Attenzione:弱键hashmap属于WeakReference类型。
弱引用类型的对象可以在Java中被垃圾收集,如果该引用不再在程序中使用。
首先让我们学习创建一个弱哈希映射。然后,我们将了解它与hashmap的区别。
为了创建一个弱哈希表,我们必须首先导入该java.util.WeakHashMap包。导入程序包后,可以使用以下方法在Java中创建弱哈希表。
// 创建WeakHashMap,容量为8,负载因子为0.6 WeakHashMap<Key, Value> numbers = new WeakHashMap<>(8, 0.6);
在上面的代码中,我们创建了一个名为numbers的WeakHashMap。
这里,
Key - 用于关联映射中每个元素(值)的唯一标识符
Value - 映射中与键关联的元素
注意new WeakHashMap<>(8,0.6)这一部分。这里,第一个参数是capacity,第二个参数是loadFactor。
capacity - 该映射的容量为8。意味着,它可以存储8个条目。
loadFactor- 此映射的负载因子为0.6。这意味着只要我们的哈希表填充了60%,条目就会被移到新哈希表中,该哈希表的大小是原始哈希表的两倍。
默认容量和负载系数
可以在不定义其容量和负载因子的情况下创建WeakHashMap。例如,
// 具有默认容量和负载因子的WeakHashMap WeakHashMap<Key, Value> numbers1 = new WeakHashMap<>();
默认,
map的容量将为 16
负载因子将为0.75
让我们看看Java中弱哈希表的实现。
import java.util.WeakHashMap; class Main { public static void main(String[] args) { // 创建名称为numbers的WeakHashMap WeakHashMap<String, Integer> numbers = new WeakHashMap<>(); String two = new String("Two"); Integer twoValue = 2; String quattro = new String("Quattro"); Integer quattroValue = 4; // Inserisci l'elemento numbers.put(two, twoValue); numbers.put(four, fourValue); System.out.println("WeakHashMap: " + numbers); //null引用 two = null; // Esegui il garbage collection System.gc(); System.out.println("Weak垃圾回收后的HashMap: " + numbers); } }
Risultato di output
WeakHashMap: {Four=4, Two=2} Weak垃圾回收后的HashMap: {Four}
Come abbiamo visto, quando la chiave 'two' della hash map debole viene impostata a null e viene eseguito il garbage collection, la chiave viene eliminata.
Questo è perché, diversamente dalla hash map, le chiavi della weak hash map appartengonoRiferimento deboleTipo. Questo significa che se l'elemento della mappa non viene più utilizzato, il garbage collector lo eliminerà. Questo è utile per risparmiare risorse.
Ora esaminiamo la stessa implementazione nella hash map.
import java.util.HashMap; class Main { public static void main(String[] args) { // Crea una hashmap di numeri pari HashMap<String, Integer> numbers = new HashMap<>(); String two = new String("Two"); Integer twoValue = 2; String quattro = new String("Quattro"); Integer quattroValue = 4; // Inserisci l'elemento numbers.put(two, twoValue); numbers.put(four, fourValue); System.out.println("HashMap: " + numbers); // Rendi il riferimento vuoto two = null; // Esegui il garbage collection System.gc(); System.out.println("HashMap dopo il garbage collection: " + numbers); } }
Risultato di output
HashMap: {Four=4, Two=2} HashMap dopo il garbage collection: {Four=4, Two=2}
In questo caso, impostare la chiave hash 'two' a null e eseguire il garbage collection non eliminerà la chiave.
Questo è perché, diversamente da WeakHashMap, le chiavi di HashMap hannoRiferimento forteTipo. Questo significa che anche se l'elemento della mappa non viene più utilizzato, l'elemento non viene eliminato dal garbage collector.
Attenzione:tutte le funzionalità di hashmap e weakhashmap sono simili, eccetto che i chiavi di weakhashmap sono riferimenti deboli, mentre le chiavi di hashmap sono riferimenti forti.
Questo è il metodo con cui possiamo creare una tabella hash debole da altre mappe.
import java.util.HashMap; import java.util.WeakHashMap; class Main { public static void main(String[] args) { // Creazione di una hashmap di numeri pari HashMap<String, Integer> evenNumbers = new HashMap<>(); String two = new String("Two"); Integer twoValue = 2; evenNumbers.put(due, dueValue); System.out.println("HashMap: " + evenNumbers); // Creazione di una mappa hash debole da una mappa hash WeakHashMap<String, Integer> numbers = new WeakHashMap<>(evenNumbers); System.out.println("WeakHashMap: " + numbers); } }
Risultato di output
HashMap: {Two=2} WeakHashMap: {Two=2}
La classe WeakHashMap fornisce metodi che permettono di eseguire varie operazioni sui mappamenti.
put() - Inserisce la mappatura chiave/valore specificata nella mappa
putAll() - Inserisce tutti gli elementi della mappatura specificata in questa mappa
putIfAbsent() - Se la mappa non contiene la chiave specificata, inserisce la mappatura chiave/valore specificata nella mappa
Ad esempio,
import java.util.WeakHashMap; class Main { public static void main(String[] args) { // Crea un WeakHashMap per numeri pari WeakHashMap<String, Integer> evenNumbers = new WeakHashMap<>(); String two = new String("Two"); Integer twoValue = 2; // Utilizzo di put() evenNumbers.put(due, dueValue); String quattro = new String("Quattro"); Integer quattroValue = 4; // Utilizzo di putIfAbsent() evenNumbers.putIfAbsent(quattro, quattroValue); System.out.println("WeakHashMap degli numeri pari: " + evenNumbers); // Creazione di una WeakHashMap chiamata numbers WeakHashMap<String, Integer> numbers = new WeakHashMap<>(); String one = new String("One"); Integer oneValue = 1; numbers.put(one, oneValue); // Utilizzo di putAll() numbers.putAll(evenNumbers); System.out.println("Numeri di WeakHashMap: " + numbers); } }
Risultato di output
WeakHashMap degli numeri pari: {Quattro=4, Due=2} Numeri di WeakHashMap: {Due=2, Quattro=4, Uno=1}
1. Utilizzo di entrySet(), keySet() e values()
entrySet() - Restituisce un insieme di tutte le mappature chiave/valore
keySet() - Restituisce l'insieme di tutte le chiavi della mappa
values() - Restituisce l'insieme di tutti i valori della mappa
Ad esempio,
import java.util.WeakHashMap; class Main { public static void main(String[] args) { // Crea un WeakHashMap per numeri pari 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); // Utilizzo di entrySet() System.out.println("Mappatura chiave/valore: " + numbers.entrySet()); // Utilizzo di keySet() System.out.println("Chiavi: " + numbers.keySet()); // Utilizzo di values() System.out.println("Valori: " + numbers.values()); } }
Risultato di output
WeakHashMap: {Two=2, One=1} Mappatura chiave/valore: [Due=2, Uno=1] Chiavi: [Two, One] Valori: [1, 2]
2. Utilizza get() e getOrDefault()
get() - Restituisce il valore associato alla chiave specificata. Se non trova la chiave, restituisce null.
getOrDefault() - Restituisce il valore associato alla chiave specificata. Se non trova la chiave, restituisce il valore predefinito specificato.
Ad esempio,
import java.util.WeakHashMap; class Main { public static void main(String[] args) { // Crea un WeakHashMap per numeri pari 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); // Utilizza get() int value1 = numbers.get("Two"); System.out.println("Utilizza il metodo get(): " + value1); // Utilizza getOrDefault() int value2 = numbers.getOrDefault("Four", 4); System.out.println("Utilizza il metodo getOrDefault(): " + value2); } }
Risultato di output
WeakHashMap: {Two=2, One=1} Utilizza il metodo get(): 2 Utilizza il metodo getOrDefault(): 4
remove(key) - Restituisce e rimuove l'elemento associato alla chiave specificata.
remove(key, value) - Rimuove la voce dalla mappatura solo se la chiave specificata è mappata al valore specificato e restituisce un valore booleano.
Ad esempio,
import java.util.WeakHashMap; class Main { public static void main(String[] args) { // Crea un WeakHashMap per numeri pari 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); // Utilizza remove() con 1 parametro int value = numbers.remove("Two"); System.out.println("Elimina valore: " + value); // Usa remove() con 2 parametri boolean result = numbers.remove("One", 3); System.out.println("L'elemento {One=3} è stato eliminato? " + result); System.out.println("WeakHashMap aggiornato: " + numbers); } }
Risultato di output
WeakHashMap: {Two=2, One=1} Elimina il valore: 2 L'elemento {One=3} è stato eliminato? False WeakHashMap aggiornato: {One=1}
Metodo | Descrizione |
---|---|
clear() | Elimina tutti gli elementi dalla mappa |
containsKey() | Controlla se la mappa contiene la chiave specificata e restituisce un valore booleano |
containsValue() | Controlla se la mappa contiene il valore specificato e restituisce un valore booleano |
size() | Restituisce la dimensione della mappa |
isEmpty() | Controlla se la mappa è vuota e restituisce un valore booleano |