📜  Java中的 EnumMap 类

📅  最后修改于: 2022-05-13 01:55:10.496000             🧑  作者: Mango

Java中的 EnumMap 类

EnumMap 是枚举类型的 Map 接口的专门实现。它扩展了 AbstractMap 并在Java中实现了 Map 接口。它属于Java .util 包。 EnumMap 的几个重要特性如下:

  • EnumMap 类是Java Collections Framework 的成员,并且不同步。
  • EnumMap 是一个有序集合,它们按照键的自然顺序进行维护(键的自然顺序是指在 enum 类型中声明枚举常量的顺序)
  • 它是一个高性能的地图实现,比 HashMap 快得多。
  • 每个 EnumMap 实例的所有键都必须是单个枚举类型的键。
  • EnumMap 不允许空键并抛出 NullPointerException 当我们尝试插入空键时。
  • 集合视图返回的迭代器是弱一致的:它们永远不会抛出 ConcurrentModificationException 并且它们可能会或可能不会显示在迭代过程中对映射进行的任何修改的影响。
  • EnumMap 在内部表示为数组。这种表示非常紧凑和高效。

语法:声明

public class EnumMap,​V> extends AbstractMap implements Serializable, Cloneable

参数:

  • 关键对象类型
  • 值对象类型

枚举映射层次结构

EnumMap-in-Java

EnumMap 的构造函数

  1. EnumMap(Class keyType):构造函数用于创建具有指定keyType的空 EnumMap。
  2. EnumMap(EnumMap m):构造函数用于创建一个与指定枚举映射keyType相同的枚举映射,初始映射与枚举映射相同
  3. EnumMap(Map m):构造函数用于创建一个枚举映射,并从参数中的指定映射初始化。

例子

Java
// Java Program to illustrate Working of EnumMap class
// and its functions
 
// Importing EnumMap class
import java.util.EnumMap;
 
// Main class
public class EnumMapExample {
 
    // Enum
    public enum GFG {
        CODE,
        CONTRIBUTE,
        QUIZ,
        MCQ;
    }
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Java EnumMap
        // Creating an empty EnumMap with key
        // as enum type state
        EnumMap gfgMap
            = new EnumMap(GFG.class);
 
        // Putting values inside EnumMap in Java
        // Inserting Enum keys different from
        // their natural order
        gfgMap.put(GFG.CODE, "Start Coding with gfg");
        gfgMap.put(GFG.CONTRIBUTE, "Contribute for others");
        gfgMap.put(GFG.QUIZ, "Practice Quizes");
        gfgMap.put(GFG.MCQ, "Test Speed with Mcqs");
 
        // Printing size of EnumMap
        System.out.println("Size of EnumMap in java: "
                           + gfgMap.size());
 
        // Printing Java EnumMap
        // Print EnumMap in natural order
        // of enum keys (order on which they are declared)
        System.out.println("EnumMap: " + gfgMap);
 
        // Retrieving value from EnumMap
        System.out.println("Key : " + GFG.CODE + " Value: "
                           + gfgMap.get(GFG.CODE));
 
        // Checking if EnumMap contains a particular key
        System.out.println(
            "Does gfgMap has " + GFG.CONTRIBUTE + ": "
            + gfgMap.containsKey(GFG.CONTRIBUTE));
 
        // Checking if EnumMap contains a particular value
        System.out.println(
            "Does gfgMap has :" + GFG.QUIZ + " : "
            + gfgMap.containsValue("Practice Quizes"));
        System.out.println("Does gfgMap has :" + GFG.QUIZ
                           + " : "
                           + gfgMap.containsValue(null));
    }
}


Java
// Java Program to Add Elements to the EnumMap
 
// Importing EnumMap class
import java.util.EnumMap;
 
// Main class
// AddingElementsToEnumMap
class GFG {
 
    enum Color { RED, GREEN, BLUE, WHITE }
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors1
            = new EnumMap<>(Color.class);
 
        // Insert elements in Map
        // using put() method
        colors1.put(Color.RED, 1);
        colors1.put(Color.GREEN, 2);
 
        // Printing mappings to the console
        System.out.println("EnumMap colors1: " + colors1);
 
        // Creating an EnumMap of the Color Enum
        EnumMap colors2
            = new EnumMap<>(Color.class);
 
        // Adding elements using the putAll() method
        colors2.putAll(colors1);
        colors2.put(Color.BLUE, 3);
 
        // Printing mappings to the console
        System.out.println("EnumMap colors2: " + colors2);
    }
}


Java
// Java Program to Access the Elements of EnumMap
 
// Importing required classes
import java.util.EnumMap;
 
// Main class
// AccessElementsOfEnumMap
class GFG {
 
    // Enum
    enum Color { RED, GREEN, BLUE, WHITE }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors
            = new EnumMap<>(Color.class);
 
        // Inserting elements using put() method
        colors.put(Color.RED, 1);
        colors.put(Color.GREEN, 2);
        colors.put(Color.BLUE, 3);
        colors.put(Color.WHITE, 4);
 
        System.out.println("EnumMap colors : " + colors);
 
        // Using the entrySet() method
        System.out.println("Key/Value mappings: "
                           + colors.entrySet());
 
        // Using the keySet() method
        System.out.println("Keys: " + colors.keySet());
 
        // Using the values() method
        System.out.println("Values: " + colors.values());
 
        // Using the get() method
        System.out.println("Value of RED : "
                           + colors.get(Color.RED));
    }
}


Java
// Java program to Remove Elements of EnumMap
 
// Importing EnumMap class
import java.util.EnumMap;
 
// Main class
class GFG {
 
    // Enum
    enum Color {
 
        // Custom elements
        RED,
        GREEN,
        BLUE,
        WHITE
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors
            = new EnumMap<>(Color.class);
 
        // Inserting elements in the Map
        // using put() method
        colors.put(Color.RED, 1);
        colors.put(Color.GREEN, 2);
        colors.put(Color.BLUE, 3);
        colors.put(Color.WHITE, 4);
 
        // Printing colors in the EnumMap
        System.out.println("EnumMap colors : " + colors);
 
        // Removing a mapping
        // using remove() Method
        int value = colors.remove(Color.WHITE);
 
        // Displaying the removed value
        System.out.println("Removed Value: " + value);
 
        // Removing specific color and storing boolean
        // if removed or not
        boolean result = colors.remove(Color.RED, 1);
 
        // Printing the boolean result whether removed or
        // not
        System.out.println("Is the entry {RED=1} removed? "
                           + result);
 
        // Printing the updated Map to the console
        System.out.println("Updated EnumMap: " + colors);
    }
}


Java
// Java Program to Replace Elements of EnumMap
 
// Importing required classes
import java.util.EnumMap;
 
// Main class
class GFG {
 
    // Enum
    enum Color {
 
        RED,
        GREEN,
        BLUE,
        WHITE
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors
            = new EnumMap<>(Color.class);
 
        // Inserting elements to Map
        // using put() method
        colors.put(Color.RED, 1);
        colors.put(Color.GREEN, 2);
        colors.put(Color.BLUE, 3);
        colors.put(Color.WHITE, 4);
 
        // Printing all elements inside above Map
        System.out.println("EnumMap colors " + colors);
 
        // Replacing certain elements depicting colors
        // using the replace() method
        colors.replace(Color.RED, 11);
        colors.replace(Color.GREEN, 2, 12);
 
        // Printing the updated elements (colors)
        System.out.println("EnumMap using replace(): "
                           + colors);
 
        // Replacing all colors using the replaceAll()
        // method
        colors.replaceAll((key, oldValue) -> oldValue + 3);
 
        // Printing the elements of above Map
        System.out.println("EnumMap using replaceAll(): "
                           + colors);
    }
}


输出
Size of EnumMap in java: 4
EnumMap: {CODE=Start Coding with gfg, CONTRIBUTE=Contribute for others, QUIZ=Practice Quizes, MCQ=Test Speed with Mcqs}
Key : CODE Value: Start Coding with gfg
Does gfgMap has CONTRIBUTE: true
Does gfgMap has :QUIZ : true
Does gfgMap has :QUIZ : false

EnumMap 的基本操作

操作 1:添加元素

为了向 EnumMap 添加元素,我们可以使用 put() 或 putAll() 方法,如下所示。

Java

// Java Program to Add Elements to the EnumMap
 
// Importing EnumMap class
import java.util.EnumMap;
 
// Main class
// AddingElementsToEnumMap
class GFG {
 
    enum Color { RED, GREEN, BLUE, WHITE }
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors1
            = new EnumMap<>(Color.class);
 
        // Insert elements in Map
        // using put() method
        colors1.put(Color.RED, 1);
        colors1.put(Color.GREEN, 2);
 
        // Printing mappings to the console
        System.out.println("EnumMap colors1: " + colors1);
 
        // Creating an EnumMap of the Color Enum
        EnumMap colors2
            = new EnumMap<>(Color.class);
 
        // Adding elements using the putAll() method
        colors2.putAll(colors1);
        colors2.put(Color.BLUE, 3);
 
        // Printing mappings to the console
        System.out.println("EnumMap colors2: " + colors2);
    }
}
输出
EnumMap colors1: {RED=1, GREEN=2}
EnumMap colors2: {RED=1, GREEN=2, BLUE=3}

操作 2:访问元素

我们可以使用 entrySet()、keySet()、values()、get() 来访问 EnumMap 的元素。下面的示例解释了这些方法。

Java

// Java Program to Access the Elements of EnumMap
 
// Importing required classes
import java.util.EnumMap;
 
// Main class
// AccessElementsOfEnumMap
class GFG {
 
    // Enum
    enum Color { RED, GREEN, BLUE, WHITE }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors
            = new EnumMap<>(Color.class);
 
        // Inserting elements using put() method
        colors.put(Color.RED, 1);
        colors.put(Color.GREEN, 2);
        colors.put(Color.BLUE, 3);
        colors.put(Color.WHITE, 4);
 
        System.out.println("EnumMap colors : " + colors);
 
        // Using the entrySet() method
        System.out.println("Key/Value mappings: "
                           + colors.entrySet());
 
        // Using the keySet() method
        System.out.println("Keys: " + colors.keySet());
 
        // Using the values() method
        System.out.println("Values: " + colors.values());
 
        // Using the get() method
        System.out.println("Value of RED : "
                           + colors.get(Color.RED));
    }
}
输出
EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}
Key/Value mappings: [RED=1, GREEN=2, BLUE=3, WHITE=4]
Keys: [RED, GREEN, BLUE, WHITE]
Values: [1, 2, 3, 4]
Value of RED : 1

操作 3:移除元素

为了删除元素,EnumMap 提供了 remove() 方法的两种变体。

例子

Java

// Java program to Remove Elements of EnumMap
 
// Importing EnumMap class
import java.util.EnumMap;
 
// Main class
class GFG {
 
    // Enum
    enum Color {
 
        // Custom elements
        RED,
        GREEN,
        BLUE,
        WHITE
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors
            = new EnumMap<>(Color.class);
 
        // Inserting elements in the Map
        // using put() method
        colors.put(Color.RED, 1);
        colors.put(Color.GREEN, 2);
        colors.put(Color.BLUE, 3);
        colors.put(Color.WHITE, 4);
 
        // Printing colors in the EnumMap
        System.out.println("EnumMap colors : " + colors);
 
        // Removing a mapping
        // using remove() Method
        int value = colors.remove(Color.WHITE);
 
        // Displaying the removed value
        System.out.println("Removed Value: " + value);
 
        // Removing specific color and storing boolean
        // if removed or not
        boolean result = colors.remove(Color.RED, 1);
 
        // Printing the boolean result whether removed or
        // not
        System.out.println("Is the entry {RED=1} removed? "
                           + result);
 
        // Printing the updated Map to the console
        System.out.println("Updated EnumMap: " + colors);
    }
}
输出
EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}
Removed Value: 4
Is the entry {RED=1} removed? true
Updated EnumMap: {GREEN=2, BLUE=3}

操作 4:更换元素

Map 接口提供了 replace() 方法的三种变体来更改 EnumMap 的映射。

例子

Java

// Java Program to Replace Elements of EnumMap
 
// Importing required classes
import java.util.EnumMap;
 
// Main class
class GFG {
 
    // Enum
    enum Color {
 
        RED,
        GREEN,
        BLUE,
        WHITE
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumMap of the Color enum
        EnumMap colors
            = new EnumMap<>(Color.class);
 
        // Inserting elements to Map
        // using put() method
        colors.put(Color.RED, 1);
        colors.put(Color.GREEN, 2);
        colors.put(Color.BLUE, 3);
        colors.put(Color.WHITE, 4);
 
        // Printing all elements inside above Map
        System.out.println("EnumMap colors " + colors);
 
        // Replacing certain elements depicting colors
        // using the replace() method
        colors.replace(Color.RED, 11);
        colors.replace(Color.GREEN, 2, 12);
 
        // Printing the updated elements (colors)
        System.out.println("EnumMap using replace(): "
                           + colors);
 
        // Replacing all colors using the replaceAll()
        // method
        colors.replaceAll((key, oldValue) -> oldValue + 3);
 
        // Printing the elements of above Map
        System.out.println("EnumMap using replaceAll(): "
                           + colors);
    }
}
输出
EnumMap colors {RED=1, GREEN=2, BLUE=3, WHITE=4}
EnumMap using replace(): {RED=11, GREEN=12, BLUE=3, WHITE=4}
EnumMap using replaceAll(): {RED=14, GREEN=15, BLUE=6, WHITE=7}

同步枚举映射

EnumMap 的实现是不同步的。这意味着如果多个线程同时访问一个树集,并且至少有一个线程修改了该集,则它必须在外部同步。这通常通过使用 Collections 类的 synchronizedMap() 方法来完成。这最好在创建时完成,以防止意外的不同步访问。

Map m = Collections.synchronizedMap(new EnumMap(...));

EnumMap 的方法

  • K - 关键对象的类型
  • V – 值对象的类型

Method

Action Performed 

clear()Removes all mappings from this map.
clone()Returns a shallow copy of this enum map.
containsKey​(Object key)Returns true if this map contains a mapping for the specified key.
containsValue​(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a Set view of the mappings contained in this map.
equals​(Object o)Compares the specified object with this map for equality.
get​(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
 hashCode()Returns the hash code value for this map.
 keySet()Returns a Set view of the keys contained in this map.
 put​(K key, V value)Associates the specified value with the specified key in this map.
 putAll​(Map m)Copies all of the mappings from the specified map to this map.
remove​(Object key)Removes the mapping for this key from this map if present.
size()Returns the number of key-value mappings in this map.
values()Returns a Collection view of the values contained in this map.

AbstractMap 类中声明的方法

Method

Description

isEmpty()Returns true if this map contains no key-value mappings.
toString()Returns a string representation of this map.

接口Java.util.Map 中声明的方法

Method

Descriptionenter 

compute​(K key, BiFunction remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
 computeIfAbsent​(K key, Function mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
 computeIfPresent​(K key, BiFunction remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
 forEach​(BiConsumer action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault​(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
merge​(K key, V value, BiFunction remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
putIfAbsent​(K key, V value)If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove​(Object key, Object value)Removes the entry for the specified key only if it is currently mapped to the specified value.
replace​(K key, V value)Replaces the entry for the specified key only if it is currently mapped to some value.
replace​(K key, V oldValue, V newValue)Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll​(BiFunction function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

EnumMap 与 EnumSet

Property

EnumMap

EnumSet

Internal RepresentationEnumMap is internally represented as arrays. The representation is compact and efficient.EnumSet is internally represented as BitVector or sequence of bits.
Permits Null Elements?Null keys are not allowed but Null values are allowed.Null elements are not permitted.
Is the Abstract Class?NoYes
InstantiationSince EnumMap is not an abstract class, it can be instantiated using the new operator.It is an abstract class, it does not have a constructor. Enum set is created using its predefined methods like allOf(), noneOf(), of(), etc.
ImplementationEnumMap is a specialized Map implementation for use with enum type keys.EnumSet is a specialized Set implementation for use with enum types.