零零乙
2009-02-03 15:41
采纳率: 50%
浏览 591
已采纳

如何初始化静态地图?

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other method?

What are the pros and cons of each?

Here is an example illustrating the two methods:

import java.util.HashMap;
import java.util.Map;

public class Test {
    private static final Map<Integer, String> myMap = new HashMap<Integer, String>();
    static {
        myMap.put(1, "one");
        myMap.put(2, "two");
    }

    private static final Map<Integer, String> myMap2 = new HashMap<Integer, String>(){
        {
            put(1, "one");
            put(2, "two");
        }
    };
}

转载于:https://stackoverflow.com/questions/507602/how-can-i-initialise-a-static-map

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

30条回答 默认 最新

  • 胖鸭 2014-07-22 18:58
    最佳回答

    The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.

    You can create an immutable map using a static initialiser too:

    public class Test {
        private static final Map<Integer, String> myMap;
        static {
            Map<Integer, String> aMap = ....;
            aMap.put(1, "one");
            aMap.put(2, "two");
            myMap = Collections.unmodifiableMap(aMap);
        }
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(29条)

相关推荐 更多相似问题