How can I safely cast a Map to a hash Map?
I want to avoid class cast exception
HashMap<String, String> hMap;
public void setHashMap(Map map){
hMap = (HashMap<String, String>) map;
}
You can make a (shallow) copy:
HashMap<String, String> copy = new HashMap<String, String>(map);
Or cast it if it's not a HashMap already:
HashMap<String, String> hashMap =
(map instanceof HashMap)
? (HashMap) map
: new HashMap<String, String>(map);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With