Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a corresponding immutable enumMap in guava?

I recently learnt about the benefits of EnumMap in Java and would like to replace the existing ImmutableMap<OccupancyType, BigDecimal> to EnumMap. However, I'd also like the immutable property offered by ImmutableMap.

  • Is there a variant, ImmutableEnumMap available in guava ?
  • In terms of storage which one (EnumMap vs ImmutableMap) performs better ?
  • I couldn't find a comparison of the two. I'd appreciate if someone can point me to a link or give some insights on the efficiency of the two data structures ?
like image 751
brainydexter Avatar asked Jun 28 '12 12:06

brainydexter


People also ask

How do you make a Java map immutable?

We used to use the unmodifiableMap() method of Collections class to create unmodifiable(immutable) Map. Map<String,String> map = new HashMap<String, String>(); Map<String,String> immutableMap = Collections. unmodifiableMap(map);


2 Answers

Guava contributor here.

Guava doesn't currently have an ImmutableEnumMap variant, but if it did, it would probably just be a wrapper around an EnumMap. (That said, slightly better immutable implementations are possible.)

EnumMap will perform better than the basic ImmutableMap, in any event; it's difficult or impossible to beat.

(I'll file an issue to investigate adding an ImmutableMap variant for enum key types, though.)


Update: Guava 14 adds Maps.immutableEnumMap().

like image 124
Louis Wasserman Avatar answered Sep 19 '22 18:09

Louis Wasserman


I was just wanted to provide an example now that ImmutableEnumMap is in Guava 14.0, because it's a package-private class, so you can't do ImmutableEnumMap.of(). You have to do Maps.immutableEnumMap() instead.

private final ImmutableMap<MyEnum, String> myEnumMap = Maps.immutableEnumMap(ImmutableMap.of(         MyEnum.A,   "A",         MyEnum.B,   "B",         MyEnum.C,   "C"         )); 

Not sure if there's a more natural syntax.

like image 34
The Alchemist Avatar answered Sep 19 '22 18:09

The Alchemist