开发者

To instantiate BiMap Of google-collections in Java

开发者 https://www.devze.com 2022-12-23 03:23 出处:网络
How can you instantiate a Bimap of Google-collections? I\'ve read the question Java: Instantiate Google Collection's HashBiMap

How can you instantiate a Bimap of Google-collections?

I've read the question Java: Instantiate Google Collection's HashBiMap

A sample of my code

import com.google.common.collect.BiMap;

public class UserSettings {

 private Map<String, Integer> wordToWordID;

 Use开发者_如何学编程rSettings() {

  this.wordToWordID = new BiMap<String. Integer>();

I get cannot instantiate the type BiMap<String, Integer>.


As stated in the linked question, you are supposed to use the create() factory methods.

In your case, this means changing

this.wordToWordID = new BiMap<String. Integer>();

to

this.wordToWordID = HashBiMap.create(); 


BiMap is an interface, and as such cannot be instantiated. You need to instantiate a concrete subclass according to the properties you want, available subclasses (according to the javadoc) are EnumBiMap, EnumHashBiMap, HashBiMap, ImmutableBiMap.


Another cool way to create a BiMap, but in this case an immutable BiMap, is using the ImmutableBiMap.Builder.

static final ImmutableBiMap<String, Integer> WORD_TO_INT =
   new ImmutableBiMap.Builder<String, Integer>()
       .put("one", 1)
       .put("two", 2)
       .put("three", 3)
       .build();

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableBiMap.html

0

精彩评论

暂无评论...
验证码 换一张
取 消