Is there a corresponding immutable enumMap in guava?

醉酒当歌 提交于 2019-11-29 05:19:11

问题


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 ?

回答1:


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().




回答2:


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.




回答3:


As the guava ImmutableEnumMap is still marked beta as of version 14, I would suggest using a unmodifiable view of a enum map and then throwing away the original reference to the enum map to ensure that it is immutable.

Example (in a constructor):

Map entries = new EnumMap <SomeEnum, T>(SomeEnum.class);
... // (fill in entries)
this.entries = Collections.unmodifiableMap(entries);


来源:https://stackoverflow.com/questions/11244402/is-there-a-corresponding-immutable-enummap-in-guava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!