Java 简明教程

Java EnumMap Class

Introduction

Java EnumMap 类是用于枚举键的专门 Map 实现。以下是关于 EnumMap 的重要要点 −

The Java EnumMap class is a specialized Map implementation for use with enum keys.Following are the important points about EnumMap −

  1. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.

  2. Enum maps are maintained in the natural order of their keys.

  3. EnumMap is not synchronized.If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally.

Class declaration

以下是 java.util.EnumMap 类的声明 −

Following is the declaration for java.util.EnumMap class −

public class EnumMap<K extends Enum<K>,V>
   extends AbstractMap<K,V>
   implements Serializable, Cloneable

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.AbstractMap

  2. java.util.Object

Adding a Key-Value to an EnumMap Of Enum, Integer Pair Example

以下示例展示了使用 Java EnumMap put(K,V) 方法在 EnumMap 实例中放入值。我们创建了一个枚举 Numbers。然后用枚举 Numbers 和 Integer 创建 EnumMap。添加很少的条目,使用 put(K,V),并打印 enumMap。再次使用 put() 方法,替换一个 enumMap 值,再次打印映射。

The following example shows the usage of Java EnumMap put(K,V) method to put a value in the EnumMap instance. We’ve created a enum Numbers. Then EnumMap is created of enum Numbers and Integer. Few entries are added using put(K,V) and enumMap is printed. Using put() method again, a value of enumMap is replaced and map is printed again.

package com.tutorialspoint;

import java.util.EnumMap;

public class EnumMapDemo {

   // create an enum
   public enum Numbers{ONE, TWO, THREE, FOUR, FIVE};

   public static void main(String[] args) {

      EnumMap<Numbers,Integer> map =
         new EnumMap<>(Numbers.class);

      // associate values in map
      map.put(Numbers.ONE, 1);
      map.put(Numbers.TWO, 2);
      map.put(Numbers.THREE,3);

      // print the whole map
      System.out.println(map);

      map.put(Numbers.THREE, 4);

      // print the updated map
      System.out.println(map);
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

{ONE=1, TWO=2, THREE=3}
{ONE=1, TWO=2, THREE=4}