views:

265

answers:

2

How can you instantiate a Bimap of Google-collections?

I know the thread.

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

+5  A: 

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(); 
Michael Myers
Hmm. Your answer raises a new question. **Why does EnumBimap not have the method `create` without parameters, like HashBiMap?**
Masi
@Masi: That's a good question. I believe the reason is because EnumBimap needs to know what its parameters are, and because of type erasure it can't know unless you pass the `Class` objects to it at some point. The same is true of `EnumMap` and `EnumSet` in the standard library.
Michael Myers
So it is not enough for `EnumMap` to know the types only. It apparently makes some processing based on the content of the input data.
Masi
Michael Myers
+4  A: 

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.

Brabster