簡體   English   中英

在 Java 中實例化 google-collections 的 BiMap

[英]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)是EnumBiMapEnumHashBiMapHashBiMapImmutableBiMap

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM