Safe cast to hash map

In general, you cannot typecast a Map to a HashMap without risk of a class-cast exception. If the Map is a TreeMap then the cast will (and must) fail.

You can avoid the exception by making using instanceof to check the type before you cast, but if the test says "not a HashMap" you are stuck. You won't be able to make the cast work.

The practical solutions are:

  • declare hMap as a Map not a HashMap,
  • copy the Map entries into a newly created HashMap, or
  • (yuck) create a custom HashMap subclass that wraps the real map.

(None of these approaches will work in all cases ... but I can't make a specific recommendation without more details of what the map is used for.)


And while you are at it, it might be appropriate to lodge a bug report with the providers of the problematic library. Forcing you to use a specific Map implementation is (on the face of it) a bad idea.


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);