Java WeakHashMap

W tym samouczku dowiemy się o Java WeakHashMap i jej działaniu na przykładach. Dowiemy się również o różnicach między WeakHashMap i HashMap

WeakHashMapKlasa zbiorów ramach Java zapewnia cechę struktury danych tabeli hash …

Implementuje interfejs Map.

Uwaga : Klucze słabego hasmapy są typu WeakReference .

Obiekt o słabym typie referencyjnym może zostać usunięty w Javie, jeśli odwołanie nie jest już używane w programie.

Nauczmy się najpierw tworzyć słabą mapę skrótów. Następnie dowiemy się, czym różni się od haszmapy.

Utwórz WeakHashMap

Aby stworzyć słaby hashmap, musimy najpierw zaimportować java.util.WeakHashMappakiet. Po zaimportowaniu pakietu, oto jak możemy stworzyć słabe hashmapy w Javie.

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

W powyższym kodzie utworzyliśmy słaby hashmap o nazwie liczby.

Tutaj,

  • Klucz - unikalny identyfikator służący do powiązania każdego elementu (wartości) na mapie
  • Wartość - elementy skojarzone z kluczami w mapie

Zwróć uwagę na część new WeakHashMap(8, 0.6). Tutaj pierwszy parametr to pojemność, a drugi parametr to loadFactor .

  • pojemność - pojemność tej mapy wynosi 8. Oznacza to, że może przechowywać 8 wpisów.
  • loadFactor - współczynnik obciążenia tej mapy wynosi 0,6. Oznacza to, że za każdym razem, gdy nasza tabela skrótów jest zapełniona w 60%, wpisy są przenoszone do nowej tabeli skrótów o rozmiarze dwukrotnie większym niż oryginalna tabela.

Domyślna pojemność i współczynnik obciążenia

Możliwe jest utworzenie słabego hashmapa bez definiowania jego pojemności i współczynnika obciążenia. Na przykład,

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

Domyślnie,

  • pojemność mapy wyniesie 16
  • współczynnik obciążenia wyniesie 0,75

Różnice między HashMap i WeakHashMap

Zobaczmy implementację słabego hashmapa w Javie.

 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); ) ) 

Wynik

 WeakHashMap: (cztery = 4, dwa = 2) WeakHashMap po wyrzuceniu elementów bezużytecznych: (cztery) 

Jak widzimy, kiedy klucz drugi słabej mapy mieszania jest ustawiony na nulli wykonuje czyszczenie pamięci, klucz jest usuwany.

Dzieje się tak, ponieważ w przeciwieństwie do hashmap, klucze słabych hashmap są słabego typu referencyjnego . Oznacza to, że wpis mapy jest usuwany przez moduł odśmiecania pamięci, jeśli klucz do tego wpisu nie jest już używany. Jest to przydatne do oszczędzania zasobów.

Zobaczmy teraz tę samą implementację w skrócie.

 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); ) ) 

Wynik

 HashMap: (Cztery = 4, Dwa = 2) HashMap po wyrzuceniu elementów bezużytecznych: (Cztery = 4, Dwa = 2) 

Tutaj, gdy klucz dwa z hashmap jest ustawiony na nulli wykonuje czyszczenie pamięci, klucz nie jest usuwany.

Dzieje się tak, ponieważ w przeciwieństwie do słabych kluczy hashmap, klucze hashmap są silnym typem referencyjnym . Oznacza to, że wpis mapy nie jest usuwany przez moduł odśmiecania pamięci, mimo że klucz do tego wpisu nie jest już używany.

Uwaga : Wszystkie funkcje haszmap i słabych haszmap są podobne, z wyjątkiem kluczy słabego haszmapy, które mają słabe odniesienie, podczas gdy klucze haszmapy są silnym odniesieniem.

Tworzenie WeakHashMap z innych map

Oto, w jaki sposób możemy stworzyć słaby hashmap z innych map.

 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); ) ) 

Wynik

 HashMap: (Dwa = 2) WeakHashMap: (Dwa = 2) 

Metody WeakHashMap

WeakHashMapKlasa udostępnia metody, które pozwalają nam na wykonywanie różnych operacji na mapie.

Wstaw elementy do WeakHashMap

  • put() - wstawia mapowanie określonego klucza / wartości do mapy
  • putAll() - wstawia wszystkie wpisy z określonej mapy do tej mapy
  • putIfAbsent() - wstawia mapowanie określonego klucza / wartości do mapy, jeśli określony klucz nie jest obecny w mapie

Na przykład,

 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); ) ) 

Wynik

 WeakHashMap liczb parzystych: (cztery = 4, dwa = 2) WeakHashMap liczb: (dwa = 2, cztery = 4, jeden = 1) 

Uzyskaj dostęp do elementów 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) Usunięta wartość: 2 Czy wpis (One = 3) został usunięty? Fałszywa aktualizacja WeakHashMap: (jeden = 1)

Inne metody WeakHashMap

metoda Opis
clear() Usuwa wszystkie wpisy z mapy
containsKey() Sprawdza, czy mapa zawiera określony klucz i zwraca wartość logiczną
containsValue() Sprawdza, czy mapa zawiera określoną wartość i zwraca wartość logiczną
size() Zwraca rozmiar mapy
isEmpty() Sprawdza, czy mapa jest pusta i zwraca wartość logiczną

Aby dowiedzieć się więcej, odwiedź stronę Java WeakHashMap (oficjalna dokumentacja Java).

Interesujące artykuły...