Šioje pamokoje pavyzdžių pagalba sužinosime apie „Java WeakHashMap“ ir jos operacijas. Taip pat sužinosime apie „WeakHashMap“ ir „HashMap“ skirtumus
„ WeakHashMap
Java“ kolekcijų sistemos klasė suteikia maišos lentelės duomenų struktūros ypatybę …
Tai įgyvendina žemėlapio sąsają.
Pastaba : Silpno maišos klavišai yra „ WeakReference“ tipo.
Silpnos nuorodos tipo objektas gali būti „Java“ surinktos šiukšlės, jei nuoroda nebenaudojama programoje.
Išmokime pirmiausia sukurti silpną maišos žemėlapį. Tada sužinosime, kuo jis skiriasi nuo hashmo.
Sukurkite „WeakHashMap“
Norėdami sukurti silpną „hashmap“, pirmiausia turime importuoti java.util.WeakHashMap
paketą. Kai importuosime paketą, štai kaip galime sukurti silpnus „Java“ hashmaps.
//WeakHashMap creation with capacity 8 and load factor 0.6 WeakHashMap numbers = new WeakHashMap(8, 0.6);
Pirmiau pateiktame kode mes sukūrėme silpną hashmap pavadintą skaičių.
Čia
- Raktas - unikalus identifikatorius, naudojamas susieti kiekvieną žemėlapio elementą (vertę)
- Vertė - elementai, susieti su klavišais žemėlapyje
Atkreipkite dėmesį į dalį new WeakHashMap(8, 0.6)
. Čia pirmasis parametras yra talpa, o antrasis - „ loadFactor“ .
- talpa - šio žemėlapio talpa yra 8. Tai reiškia, kad jame galima išsaugoti 8 įrašus.
- loadFactor - šio žemėlapio apkrovos koeficientas yra 0,6. Tai reiškia, kad kiekvieną kartą, kai mūsų maišos lentelė užpildoma 60%, įrašai perkeliami į naują maišos lentelę, kurios dydis yra dvigubai didesnis nei originalios maišos lentelės.
Numatytasis pajėgumas ir apkrovos koeficientas
Nenustatant jo talpos ir apkrovos koeficiento, galima sukurti silpną „hashmap“. Pavyzdžiui,
// WeakHashMap with default capacity and load factor WeakHashMap numbers1 = new WeakHashMap();
Pagal numatytuosius nustatymus
- žemėlapio talpa bus 16
- apkrovos koeficientas bus 0,75
„HashMap“ ir „WeakHashMap“ skirtumai
Pažiūrėkime, kaip „Java“ įdiegtas silpnas „hashmap“.
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); ) )
Rezultatas
„WeakHashMap“: (keturi = 4, du = 2) „WeakHashMap“ po šiukšlių surinkimo: (keturi)
Kaip matome, kai nustatytas silpno „hashmap“ raktas null
ir atliekamas šiukšlių surinkimas, raktas pašalinamas.
Taip yra todėl, kad, skirtingai nei „hashmaps“, silpnų „hashmaps“ klavišų tipas yra silpnas . Tai reiškia, kad šiukšlių surinkėjas pašalina žemėlapio įrašą, jei to įrašo raktas nebenaudojamas. Tai naudinga taupant išteklius.
Dabar pamatykime tą patį įgyvendinimą 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); ) )
Rezultatas
HashMap: (Keturi = 4, Du = 2) HashMap po šiukšlių surinkimo: (Keturi = 4, Du = 2)
Čia, kai antrasis „hashmap“ raktas yra nustatytas null
ir atliekamas šiukšlių surinkimas, raktas nepašalinamas.
Taip yra todėl, kad skirtingai nei silpni „hashmaps“, „hashmaps“ klavišai yra tvirtos nuorodos tipo. Tai reiškia, kad šiukšlių surinkėjas nepašalina žemėlapio įrašo, nors to įrašo raktas nebenaudojamas.
Pastaba : visos hasmas ir silpnos maišos funkcijos yra panašios, išskyrus tai, kad silpno hasmo žemėlapio klavišai yra silpnos nuorodos, tuo tarpu maišos schemos klavišai yra stiprūs.
„WeakHashMap“ kūrimas iš kitų žemėlapių
Štai kaip mes galime sukurti silpną hashmap iš kitų žemėlapių.
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); ) )
Rezultatas
HashMap: (Du = 2) WeakHashMap: (Du = 2)
WeakHashMap metodai
WeakHashMap
Klasė suteikia metodus, kurie leidžia mums atlikti įvairius darbus žemėlapyje.
Įdėkite elementus į „WeakHashMap“
put()
- įterpia nurodytą raktų / reikšmių žemėlapį į žemėlapįputAll()
- įterpia visus įrašus iš nurodyto žemėlapio į šį žemėlapįputIfAbsent()
- įterpia nurodytą rakto / vertės atvaizdavimą į žemėlapį, jei nurodyto rakto žemėlapyje nėra
Pavyzdžiui,
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); ) )
Rezultatas
Lygių skaičių žemėlapis „WeakHash“: (Keturi = 4, Du = 2) „WeakHashMap“ skaičių skaičiai: (Du = 2, Keturi = 4, Vienas = 1)
Prieiga prie „WeakHashMap“ elementų
1. Using entrySet(), keySet() and values()
entrySet()
- returns a set of all the key/value mapping of the mapkeySet()
- returns a set of all the keys of the mapvalues()
- 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. Returnsnull
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 mapremove(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: (Du = 2, Vienas = 1) Pašalinta reikšmė: 2 Ar įrašas (Vienas = 3) pašalintas? Klaidingai atnaujinta „WeakHashMap“: (vienas = 1)
Kiti WeakHashMap metodai
Metodas | apibūdinimas |
---|---|
clear() | Pašalina visus įrašus iš žemėlapio |
containsKey() | Tikrina, ar žemėlapyje yra nurodytas raktas, ir pateikia loginę vertę |
containsValue() | Tikrina, ar žemėlapyje yra nurodyta reikšmė, ir pateikia loginę vertę |
size() | Grąžina žemėlapio dydį |
isEmpty() | Patikrina, ar žemėlapis tuščias, ir pateikia loginę vertę |
Norėdami sužinoti daugiau, apsilankykite „Java WeakHashMap“ (oficiali „Java“ dokumentacija).