Question

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;

 UserSettings() {

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

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

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top