如何安全地将Map转换为哈希映射?
我想避免类强制转换异常
HashMap<String, String> hMap; public void setHashMap(Map map){ hMap = (HashMap<String, String>) map; }
如果你想制作一个(浅)副本:
HashMap<String, String> copy = new HashMap<String, String>(map);
如果你只想在它还不是HashMap时才这样做:
HashMap<String, String> hashMap = (map instanceof HashMap) ? (HashMap) map : new HashMap<String, String>(map);
翻译自:https://stackoverflow.com/questions/13924825/safe-cast-to-hash-map