【问题标题】:How to initialize a public static final read-only LinkedMap (bidirectionnal map)如何初始化公共静态最终只读链接地图(双向地图)
【发布时间】:2012-05-23 18:27:19
【问题描述】:

我想创建一个

public static final LinkedMap myMap;

我在某个地方发现了与地图类似的东西:

 public class Test {
        private static final Map<Integer, String> MY_MAP = createMap();

        private static Map<Integer, String> createMap() {
            Map<Integer, String> result = new HashMap<Integer, String>();
            result.put(1, "one");
            result.put(2, "two");
            return Collections.unmodifiableMap(result);
        }
    }

但我不能将'unmodifiableMap' 方法应用于LinkedMap。有谁能够帮我?有可能吗?

【问题讨论】:

  • 您需要特定于LinkedMap 的方法吗?否则只需将 myMap 声明为 Map
  • 我需要一个 LinkedMap,因为它具有双向性(我应该提到它来自 commons.apache.org.collections)。

标签: java map final apache-commons-collection


【解决方案1】:

最流行的解决方法几乎可以肯定是GuavaImmutableMap。 (披露:我为 Guava 做出了贡献。)

Map<Integer, String> map = ImmutableMap.of(
  1, "one",
  2, "two");

ImmutableMap<Integer, String> map = ImmutableMap
  .<Integer, String> builder()
  .put(1, "one")
  .put(2, "two")
  .build();

如果没有其他库,除了您编写的库之外,唯一的解决方法是

static final Map<Integer, String> CONSTANT_MAP;
static {
  Map<Integer, String> tmp = new LinkedHashMap<Integer, String>();
  tmp.put(1, "one");
  tmp.put(2, "two");
  CONSTANT_MAP = Collections.unmodifiableMap(tmp);
}

【讨论】:

  • ImmutableMap 是否提供双向性?
  • 如果你想要双向性——你的意思是“双向”what I think you mean——那么ImmutableBiMap会做到这一点。
  • 所以,如果我需要某个值的键,我必须先检索映射的逆,对吗?
  • 是的,但这是一个简单的恒定时间操作:map.inverse().get(value)
【解决方案2】:

声明等于函数 Create() 的变量对我来说没有任何意义。

如果你需要一个最终变量 myMap,你必须这样写:

// = createMap();
private final static LinkedHashMap<Integer, String> 
                                          myMap = new LinkedHashMap<Integer, String>();
static {
    myMap.put(1, "one");
    myMap.put(2, "Two");
};

public static void main(String[] args) {

  for( String link : myMap.values()){
    System.out.println("Value in myMap: "+link);
  }

}

或者如果你想使用 create() 函数,你必须从 myMap 中去掉 final 关键字,并在 main 中使用 myMap,例如:

    public static void main(String[] args) {

    myMap = Test.createMap();

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多