Stainedart
Stainedart

Reputation: 1969

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

Upvotes: 19

Views: 55329

Answers (6)

Thilo
Thilo

Reputation: 262474

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

Upvotes: 42

Stephen C
Stephen C

Reputation: 718758

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.

Upvotes: 4

Brian
Brian

Reputation: 17299

If you're going to always assume that it's a HashMap<String, String>, why not just do this?

HashMap<String, String> hMap;

public void setHashMap(HashMap<String, String> map){
    hMap = map;
}

If you want something more generic that will accept any Map:

public void setHashMap(Map<String, String> map){
    if (map != null)
        hMap = new HashMap<String, String>(map);
    else
        hMap = new HashMap<String, String>();
}

No casting required. Also, your example was missing the return type. I've assumed that you meant to put void.

Upvotes: 0

Bhavik Ambani
Bhavik Ambani

Reputation: 6657

Your function should be as below to avoid any kind of exception such as ClassCastException or NullPointerException. Here any kind of Map object will be assigned to HashMap into your field of the class.

public void setHashMap(Map<String, String> map) {

    if (map != null && map instanceof HashMap<?, ?>) {
        hMap = (HashMap<String, String>) map;
    } else if (map != null) {
        hMap.putAll(map);
    }
}

Upvotes: 3

AlexWien
AlexWien

Reputation: 28727

You should not cast to HashMap! Cast to Map!
If you really have a reason for your question, then, you have to create a new HashMap in case Map is not an instance of Map.
But this is a bad idea.

Upvotes: 1

palako
palako

Reputation: 3470

You can do:

if (map instanceof HashMap) {
   hMap = (HashMap<String, String>) map;
} else {
  //do whatever you want instead of throwing an exception
}

or just surround the cast with a try/catch and capture the exception when it happens.

Upvotes: 0

Related Questions