Convert Map to Map

后端 未结 11 1838
暗喜
暗喜 2021-01-31 13:27

How can I convert Map to Map ?

This does not work:

Map map = ne         


        
11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 14:19

    There are two ways to do this. One is very simple but unsafe:

    Map map = new HashMap();
    Map newMap = new HashMap((Map)map);  // unchecked warning
    

    The other way has no compiler warnings and ensures type safety at runtime, which is more robust. (After all, you can't guarantee the original map contains only String values, otherwise why wouldn't it be Map in the first place?)

    Map map = new HashMap();
    Map newMap = new HashMap();
    @SuppressWarnings("unchecked") Map intermediate =
        (Map)Collections.checkedMap(newMap, String.class, String.class);
    intermediate.putAll(map);
    

提交回复
热议问题