adding multiple entries to a HashMap at once in one statement

前端 未结 9 975
迷失自我
迷失自我 2020-12-04 06:27

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

  hashMap.put(\"One\", new Integer(1)); // add         


        
9条回答
  •  没有蜡笔的小新
    2020-12-04 06:58

    You can use the Double Brace Initialization as shown below:

    Map hashMap = new HashMap()
    {{
         put("One", 1);
         put("Two", 2);
         put("Three", 3);
    }};
    

    As a piece of warning, please refer to the thread Efficiency of Java “Double Brace Initialization" for the performance implications that it might have.

提交回复
热议问题