Better Map Constructor

后端 未结 5 647
走了就别回头了
走了就别回头了 2021-01-02 10:13

Is there a more streamlined way to do the following?

Map map = new HashMap();
map.put(\"a\", \"apple\");
map.put(         


        
5条回答
  •  攒了一身酷
    2021-01-02 10:44

    There's always double-brace initialization:

    Map map = new HashMap(){{
        put("a", "apple"); put("b", "bear"); put("c", "cat");}};
    

    There are problems with this approach. It returns an anonymous inner class extending HashMap, not a HashMap. If you need to serialize the map then know that serialization of inner classes is discouraged.

提交回复
热议问题