Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe cast to hash map

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;
}
like image 763
Stainedart Avatar asked Dec 18 '12 01:12

Stainedart


1 Answers

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);
like image 71
Thilo Avatar answered Sep 21 '22 12:09

Thilo