[英]To instantiate BiMap Of google-collections in Java
如何實例化 Google 集合的Bimap
?
我已經閱讀了問題Java: Instantiate Google Collection's HashBiMap
我的代碼示例
import com.google.common.collect.BiMap;
public class UserSettings {
private Map<String, Integer> wordToWordID;
UserSettings() {
this.wordToWordID = new BiMap<String. Integer>();
我cannot instantiate the type BiMap<String, Integer>
。
如鏈接問題所述,您應該使用create()
工廠方法。
在你的情況下,這意味着改變
this.wordToWordID = new BiMap<String. Integer>();
到
this.wordToWordID = HashBiMap.create();
BiMap是一個接口,因此無法實例化。 您需要根據所需的屬性實例化一個具體的子類,可用的子類(根據 javadoc)是EnumBiMap 、 EnumHashBiMap 、 HashBiMap 、 ImmutableBiMap 。
創建 BiMap 的另一種很酷的方法,但在這種情況下是不可變的 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.