How to directly initialize a HashMap (in a literal way)?

后端 未结 14 2371
野趣味
野趣味 2020-11-22 10:58

Is there some way of initializing a Java HashMap like this?:

Map test = 
    new HashMap{\"test\":\"test\",\"test\         


        
14条回答
  •  隐瞒了意图╮
    2020-11-22 11:25

    There is no direct way to do this - Java has no Map literals (yet - I think they were proposed for Java 8).

    Some people like this:

    Map test = new HashMap(){{
           put("test","test"); put("test","test");}};
    

    This creates an anonymous subclass of HashMap, whose instance initializer puts these values. (By the way, a map can't contain twice the same value, your second put will overwrite the first one. I'll use different values for the next examples.)

    The normal way would be this (for a local variable):

    Map test = new HashMap();
    test.put("test","test");
    test.put("test1","test2");
    

    If your test map is an instance variable, put the initialization in a constructor or instance initializer:

    Map test = new HashMap();
    {
        test.put("test","test");
        test.put("test1","test2");
    }
    

    If your test map is a class variable, put the initialization in a static initializer:

    static Map test = new HashMap();
    static {
        test.put("test","test");
        test.put("test1","test2");
    }
    

    If you want your map to never change, you should after the initialization wrap your map by Collections.unmodifiableMap(...). You can do this in a static initializer too:

    static Map test;
    {
        Map temp = new HashMap();
        temp.put("test","test");
        temp.put("test1","test2");
        test = Collections.unmodifiableMap(temp);
    }
    

    (I'm not sure if you can now make test final ... try it out and report here.)

提交回复
热议问题