2

Answer/Edit:

Ok, just realized I was trying to use the EnumBiMap incorrectly. I wanted a bi map that does not allow null values, which I guess the Guava library does not have. I looked at ImmutableBiMap but it is supposed to be static, with non-changing values. Guess I'll just have to check for null before I put anything into a HashBiMap.

That said, this is how you can instantiate/use EnumBiMap:

Given enum:

enum Test{
    VAL;
}  

Use:

Map<Test, Test> m = EnumBiMap.create(Test.class, Test.class);
m.put(Test.VAL, Test.VAL);

Or, if you want a more generic EnumBiMap, that supports any enum type:

Map<Enum, Enum> m = EnumBiMap.create(Enum.class, Enum.class);
m.put(Test.VAL, Test2.VAL2);

Original question:

I have looked around the Guava API documentation and the web, but cannot find any examples of implementing the EnumBiMap class. It doesn't behave the same as HashBiMap, which I could easily instantiate. Here is what I've tried - none of these will compile for me:

Map<Integer, String> m = EnumBiMap.create();

..similar to what is suggested here: Java: Instantiate Google Collection's HashBiMap

Also tried:

Map<Integer, String> m = EnumBiMap.<Integer, String>create();

..similar to formatting here: Google Guava: How to use ImmutableSortedMap.naturalOrder?

And:

Map<Integer, String> m = EnumBiMap.create(Integer.class, String.class);

Has anyone successfully implemented EnumBiMap or seen any examples? If so, how?

Community
  • 1
  • 1
etech
  • 2,548
  • 1
  • 27
  • 24

1 Answers1

8

Do you mean (Guava version 14.0):

Map<Test, Test> m = EnumBiMap.create(Test.class, Test.class);
m.put(Test.VAL, Test.VAL);

And please notice the signature:

<K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Class<K> keyType, Class<V> valueType)

So Integer and String are not suitable for K or V.

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130