Java EnumMap

In questo tutorial, impareremo a conoscere la classe Java EnumMap e le sue operazioni con l'aiuto di esempi.

La EnumMapclasse del framework delle collezioni Java fornisce un'implementazione della mappa per gli elementi di un enum.

In EnumMap, gli elementi enum vengono usati come chiavi . Implementa l'interfaccia Map.

Prima di saperne di più EnumMap, assicurati di conoscere Java Enums.

Creazione di una EnumMap

Per creare una mappa enum, dobbiamo java.util.EnumMapprima importare il pacchetto. Una volta importato il pacchetto, ecco come possiamo creare mappe enum in Java.

 enum Size ( SMALL, MEDIUM, LARGE, EXTRALARGE ) EnumMap sizes = new EnumMap(Size.class); 

Nell'esempio precedente, abbiamo creato una mappa enum denominata size.

Qui,

  • Size: chiavi dell'enumerazione mappate ai valori
  • Intero: valori della mappa enum associata alle chiavi corrispondenti

Metodi di EnumMap

La EnumMapclasse fornisce metodi che ci consentono di eseguire vari elementi sulle mappe enum.

Inserisci elementi in EnumMap

  • put() - inserisce la mappatura chiave / valore specificata (voce) nella mappa enum
  • putAll() - inserisce tutte le voci di una mappa specificata in questa mappa

Per esempio,

 import java.util.EnumMap; class Main ( enum Size ( SMALL, MEDIUM, LARGE, EXTRALARGE ) public static void main(String() args) ( // Creating an EnumMap of the Size enum EnumMap sizes1 = new EnumMap(Size.class); // Using the put() Method sizes1.put(Size.SMALL, 28); sizes1.put(Size.MEDIUM, 32); System.out.println("EnumMap1: " + sizes1); EnumMap sizes2 = new EnumMap(Size.class); // Using the putAll() Method sizes2.putAll(sizes1); sizes2.put(Size.LARGE, 36); System.out.println("EnumMap2: " + sizes2); ) ) 

Produzione

 EnumMap1: (SMALL = 28, MEDIUM = 32) EnumMap2: (SMALL = 28, MEDIUM = 32, LARGE = 36) 

Nell'esempio precedente, abbiamo utilizzato il putAll()metodo per inserire tutti gli elementi di una mappa enum size1 in una mappa enum di size2.

È anche possibile inserire elementi di altre mappe quali HashMap, TreeMapeccetera in carta enum utilizzando putAll(). Tuttavia, tutte le mappe dovrebbero essere dello stesso tipo enum.

Accedi agli elementi di EnumMap

1. Utilizzo di entrySet (), keySet () e values ​​()

  • entrySet() - restituisce un insieme di tutte le chiavi / valori di mappatura (voce) di una mappa enum
  • keySet() - restituisce un insieme di tutte le chiavi di una mappa enum
  • values() - restituisce un insieme di tutti i valori di una mappa enum

Per esempio,

 import java.util.EnumMap; class Main ( enum Size ( SMALL, MEDIUM, LARGE, EXTRALARGE ) public static void main(String() args) ( // Creating an EnumMap of the Size enum EnumMap sizes = new EnumMap(Size.class); sizes.put(Size.SMALL, 28); sizes.put(Size.MEDIUM, 32); sizes.put(Size.LARGE, 36); sizes.put(Size.EXTRALARGE, 40); System.out.println("EnumMap: " + sizes); // Using the entrySet() Method System.out.println("Key/Value mappings: " + sizes.entrySet()); // Using the keySet() Method System.out.println("Keys: " + sizes.keySet()); // Using the values() Method System.out.println("Values: " + sizes.values()); ) ) 

Produzione

 EnumMap: (SMALL = 28, MEDIUM = 32, LARGE = 36, EXTRALARGE = 40) Mappature chiave / valore: (SMALL = 28, MEDIUM = 32, LARGE = 36, EXTRALARGE = 40) Tasti: (SMALL, MEDIUM, LARGE, EXTRALARGE) Valori: (28, 32, 36, 40) 

2. Utilizzo del metodo get ()

Il get()metodo restituisce il valore associato alla chiave specificata. Restituisce nullse la chiave specificata non viene trovata.

Per esempio,

 import java.util.EnumMap; class Main ( enum Size ( SMALL, MEDIUM, LARGE, EXTRALARGE ) public static void main(String() args) ( // Creating an EnumMap of the Size enum EnumMap sizes = new EnumMap(Size.class); sizes.put(Size.SMALL, 28); sizes.put(Size.MEDIUM, 32); sizes.put(Size.LARGE, 36); sizes.put(Size.EXTRALARGE, 40); System.out.println("EnumMap: " + sizes); // Using the get() Method int value = sizes.get(Size.MEDIUM); System.out.println("Value of MEDIUM: " + value); ) ) 

Produzione

 EnumMap: (SMALL = 28, MEDIUM = 32, LARGE = 36, EXTRALARGE = 40) Valore di MEDIUM: 32 

Rimuovi elementi EnumMap

  • remove(key) - restituisce e rimuove dalla mappa la voce associata alla chiave specificata
  • remove(key, value) - rimuove la voce dalla mappa solo se la chiave specificata è stata mappata al valore specificato e restituisce un valore booleano

Per esempio,

 import java.util.EnumMap; class Main ( enum Size ( SMALL, MEDIUM, LARGE, EXTRALARGE ) public static void main(String() args) ( // Creating an EnumMap of the Size enum EnumMap sizes = new EnumMap(Size.class); sizes.put(Size.SMALL, 28); sizes.put(Size.MEDIUM, 32); sizes.put(Size.LARGE, 36); sizes.put(Size.EXTRALARGE, 40); System.out.println("EnumMap: " + sizes); // Using the remove() Method int value = sizes.remove(Size.MEDIUM); System.out.println("Removed Value: " + value); boolean result = sizes.remove(Size.SMALL, 28); System.out.println("Is the entry (SMALL=28) removed? " + result); System.out.println("Updated EnumMap: " + sizes); ) ) 

Produzione

EnumMap: (SMALL = 28, MEDIUM = 32, LARGE = 36, EXTRALARGE = 40) Valore rimosso: 32 La voce (SMALL = 28) è stata rimossa? True Aggiornato EnumMap: (LARGE = 36, EXTRALARGE = 40)

Sostituisci elementi EnumMap

  • replace(key, value) - sostituisce il valore associato alla chiave specificata con il nuovo valore
  • replace(key, old, new) - sostituisce il vecchio valore con il nuovo valore solo se il vecchio valore è già associato alla chiave specificata
  • replaceAll(function) - sostituisce ogni valore della mappa con il risultato della funzione specificata
 import java.util.EnumMap; class Main ( enum Size ( SMALL, MEDIUM, LARGE, EXTRALARGE ) public static void main(String() args) ( // Creating an EnumMap of the Size enum EnumMap sizes = new EnumMap(Size.class); sizes.put(Size.SMALL, 28); sizes.put(Size.MEDIUM, 32); sizes.put(Size.LARGE, 36); sizes.put(Size.EXTRALARGE, 40); System.out.println("EnumMap: " + sizes); // Using the replace() Method sizes.replace(Size.MEDIUM, 30); sizes.replace(Size.LARGE, 36, 34); System.out.println("EnumMap using replace(): " + sizes); // Using the replaceAll() Method sizes.replaceAll((key, oldValue) -> oldValue + 3); System.out.println("EnumMap using replaceAll(): " + sizes); ) ) 

Produzione

 EnumMap: (SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40) EnumMap using replace(): (SMALL=28, MEDIUM=30, LARGE=34, EXTRALARGE=40) EnumMap using replaceAll(): (SMALL=31, MEDIUM=33, LARGE=37, EXTRALARGE=43) 

In the above program, notice the statement

 sizes.replaceAll((key, oldValue) -> oldValue + 3); 

Here, the method accesses all the entries of the map. It then replaces all the values with the new values provided by the lambda expressions.

Other Methods

Method Description
clone() Creates a copy of the EnumMap
containsKey() Searches the EnumMap for the specified key and returns a boolean result
containsValue() Searches the EnumMap for the specified value and returns a boolean result
size() Returns the size of the EnumMap
clear() Removes all the entries from the EnumMap

EnumSet Vs. EnumMap

Both the EnumSet and EnumMap class provides data structures to store enum values. However, there exist some major differences between them.

  • Enum set is represented internally as a sequence of bits, whereas the enum map is represented internally as arrays.
  • Enum set is created using its predefined methods like allOf(), noneOf(), of(), etc. However, an enum map is created using its constructor.

Clonable and Serializable Interfaces

The EnumMap class also implements Cloneable and Serializable interfaces.

Cloneable Interface

It allows the EnumMap class to make a copy of instances of the class.

Serializable Interface

Whenever Java objects need to be transmitted over a network, objects need to be converted into bits or bytes. This is because Java objects cannot be transmitted over the network.

L' Serializableinterfaccia consente di serializzare le classi. Ciò significa che gli oggetti delle classi implementate Serializablepossono essere convertiti in bit o byte.

Articoli interessanti...