javaguavaenum-map

How to initialize empty ImmutableEnumMap using guava?


I have a constructor which takes Map<ProcessInfoEnum, String> as a parameter. So I am initializing NO_OPERATION variable like as shown below with empty immutable map.

  public static final Processor NO_OPERATION = new Processor(ImmutableMap.<ProcessInfoEnum, String>of());
  private final Map<ProcessInfoEnum, String> values;

  public Processor(Map<ProcessInfoEnum, String> values) {
    this.values = values;
  }

Now I have changed my constructor to use EnumMap as shown below due to some design change:

  public Processor(EnumMap<ProcessInfoEnum, String> values) {
    this.values = values;
  }

Now how can I write same equivalent line for NO_OPERATION but with ImmutableEnumMap so that it can initialize empty immutable enum map?

  // obviously this doesn't work
  public static final Processor NO_OPERATION = new Processor(ImmutableEnumMap.<ProcessInfoEnum, String>of());
  private final EnumMap<ProcessInfoEnum, String> values;

  public Processor(EnumMap<ProcessInfoEnum, String> values) {
    this.values = values;
  }

Since ImmutableEnumMap is a package-private class so I cannot do ImmutableEnumMap.of(). Is there any other way?


Solution

  • There is no public ImmutableEnumMap type, so you'd have to type it as ImmutableMap anyway - so you can just use ImmutableMap.of() without worrying about the enum part. There is no difference.