在 Java 中实例化 google-collections 的 BiMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2428955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:06:14  来源:igfitidea点击:

To instantiate BiMap Of google-collections in Java

javaguavabimap

提问by Léo Léopold Hertz ??

How can you instantiate a Bimapof Google-collections?

如何实例化一个BimapGoogle 集合?

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

我已经阅读了问题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>.

我明白了cannot instantiate the type BiMap<String, Integer>

回答by Michael Myers

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

如链接问题所述,您应该使用create()工厂方法。

In your case, this means changing

在你的情况下,这意味着改变

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

to

this.wordToWordID = HashBiMap.create(); 

回答by brabster

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

BiMap是一个接口,因此无法实例化。您需要根据所需的属性实例化一个具体的子类,可用的子类(根据 javadoc)是EnumBiMapEnumHashBiMapHashBiMapImmutableBiMap

回答by Joao Sousa

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

创建 BiMap 的另一种很酷的方法是使用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

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