简体   繁体   中英

How to instantiate guava EnumBiMap?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM