Java WeakHashMap

In questo tutorial, impareremo a conoscere Java WeakHashMap e le sue operazioni con l'aiuto di esempi. Impareremo anche le differenze tra WeakHashMap e HashMap

La WeakHashMapclasse del framework delle collezioni Java fornisce la funzionalità della struttura dei dati della tabella hash …

Implementa l'interfaccia Map.

Nota : le chiavi dell'hashmap debole sono di tipo WeakReference .

L'oggetto di un tipo di riferimento debole può essere sottoposto a garbage collection in Java se il riferimento non viene più utilizzato nel programma.

Impariamo prima a creare una mappa hash debole. Quindi, impareremo come differisce da una hashmap.

Crea una WeakHashMap

Per creare una hashmap debole, dobbiamo java.util.WeakHashMapprima importare il pacchetto. Una volta importato il pacchetto, ecco come possiamo creare hashmap deboli in Java.

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

Nel codice sopra, abbiamo creato una hashmap debole denominata numeri.

Qui,

  • Chiave: un identificatore univoco utilizzato per associare ogni elemento (valore) in una mappa
  • Valore: elementi associati da chiavi in ​​una mappa

Nota la parte new WeakHashMap(8, 0.6). Qui, il primo parametro è la capacità e il secondo parametro è loadFactor .

  • capacità - La capacità di questa mappa è 8. Ciò significa che può memorizzare 8 voci.
  • loadFactor - Il fattore di carico di questa mappa è 0,6. Ciò significa che ogni volta che la nostra tabella hash viene riempita del 60%, le voci vengono spostate in una nuova tabella hash di dimensioni doppie rispetto alla tabella hash originale.

Capacità e fattore di carico predefiniti

È possibile creare una hashmap debole senza definirne la capacità e il fattore di carico. Per esempio,

 // WeakHashMap with default capacity and load factor WeakHashMap numbers1 = new WeakHashMap(); 

Per impostazione predefinita,

  • la capacità della mappa sarà 16
  • il fattore di carico sarà 0,75

Differenze tra HashMap e WeakHashMap

Vediamo l'implementazione di una hashmap debole in Java.

 import java.util.WeakHashMap; class Main ( public static void main(String() args) ( // Creating WeakHashMap of numbers WeakHashMap 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); ) ) 

Produzione

 WeakHashMap: (Quattro = 4, Due = 2) WeakHashMap dopo la raccolta dei rifiuti: (Quattro) 

Come possiamo vedere, quando la chiave due di una hashmap debole è impostata su nulled esegue la garbage collection, la chiave viene rimossa.

È perché, a differenza delle hashmap, le chiavi delle hashmap deboli sono di tipo di riferimento debole . Ciò significa che la voce di una mappa viene rimossa dal garbage collector se la chiave per quella voce non viene più utilizzata. Questo è utile per risparmiare risorse.

Vediamo ora la stessa implementazione in una hashmap.

 import java.util.HashMap; class Main ( public static void main(String() args) ( // Creating HashMap of even numbers HashMap 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); ) ) 

Produzione

 HashMap: (Quattro = 4, Due = 2) HashMap dopo la raccolta dei rifiuti: (Quattro = 4, Due = 2) 

Qui, quando la chiave due dell'hashmap è impostata su nulled esegue la garbage collection, la chiave non viene rimossa.

Questo perché, a differenza degli hashmap deboli, le chiavi degli hashmap sono di tipo di riferimento forte . Ciò significa che la voce di una mappa non viene rimossa dal garbage collector anche se la chiave per quella voce non viene più utilizzata.

Nota : tutte le funzionalità di hashmap e hashmap deboli sono simili tranne che le chiavi di una hashmap debole sono di riferimento debole, mentre le chiavi di una hashmap sono di forte riferimento.

Creazione di WeakHashMap da altre mappe

Ecco come possiamo creare una hashmap debole da altre mappe.

 import java.util.HashMap; import java.util.WeakHashMap; class Main ( public static void main(String() args) ( // Creating a hashmap of even numbers HashMap 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 numbers = new WeakHashMap(evenNumbers); System.out.println("WeakHashMap: " + numbers); ) ) 

Produzione

 HashMap: (Due = 2) WeakHashMap: (Due = 2) 

Metodi di WeakHashMap

La WeakHashMapclasse fornisce metodi che ci consentono di eseguire varie operazioni sulla mappa.

Inserisci elementi in WeakHashMap

  • put() - inserisce la mappatura chiave / valore specificata nella mappa
  • putAll() - inserisce tutte le voci dalla mappa specificata a questa mappa
  • putIfAbsent() - inserisce la mappatura chiave / valore specificata nella mappa se la chiave specificata non è presente nella mappa

Per esempio,

 import java.util.WeakHashMap; class Main ( public static void main(String() args) ( // Creating WeakHashMap of even numbers WeakHashMap 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 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); ) ) 

Produzione

 WeakHashMap dei numeri pari: (Four = 4, Two = 2) WeakHashMap dei numeri: (Two = 2, Four = 4, One = 1) 

Accedi agli elementi WeakHashMap

1. Using entrySet(), keySet() and values()

  • 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

For example,

 import java.util.WeakHashMap; class Main ( public static void main(String() args) ( // Creating WeakHashMap of even numbers WeakHashMap 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()); ) ) 

Output

 WeakHashMap: (Two=2, One=1) Key/Value mappings: (Two=2, One=1) Keys: (Two, One) Values: (1, 2) 

2. Using get() and 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.

For example,

 import java.util.WeakHashMap; class Main ( public static void main(String() args) ( // Creating WeakHashMap of even numbers WeakHashMap 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); ) ) 

Output

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

Remove WeakHashMap Elements

  • 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

For example,

 import java.util.WeakHashMap; class Main ( public static void main(String() args) ( // Creating WeakHashMap of even numbers WeakHashMap 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); ) ) 

Output

WeakHashMap: (Two = 2, One = 1) Valore rimosso: 2 La voce (One = 3) è stata rimossa? Falso WeakHashMap aggiornato: (uno = 1)

Altri metodi di WeakHashMap

Metodo Descrizione
clear() Rimuove tutte le voci dalla mappa
containsKey() Verifica se la mappa contiene la chiave specificata e restituisce un valore booleano
containsValue() Verifica 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

Per saperne di più, visita Java WeakHashMap (documentazione Java ufficiale).

Articoli interessanti...