Secure hash transfer

How can I safely use a map for a hash map?

I want to throw cast class exception

HashMap<String, String> hMap; public void setHashMap(Map map){ hMap = (HashMap<String, String>) map; } 
+6
source share
6 answers

If you want to make a (shallow) copy:

 HashMap<String, String> copy = new HashMap<String, String>(map); 

If you want to do this only when it is not a HashMap:

 HashMap<String, String> hashMap = (map instanceof HashMap) ? (HashMap) map : new HashMap<String, String>(map); 
+18
source

Your function should be like below to avoid any exceptions like ClassCastException or NullPointerException . Here, any type of Map object will be assigned a HashMap in the field of your 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); } } 
+2
source

In general, you cannot resort to titrating Map in HashMap without the risk of class exclusion. If Map is a TreeMap , then the cast will (and should) fail.

You can avoid the exception by using instanceof to check the type before making the throw, but if the test says "not a HashMap", you are stuck. You cannot do acting work.

Practical solutions:

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

(None of these approaches will work in all cases ... but I cannot make a specific recommendation, no more detailed information about what the map is used for.)


And while you are on it, it might be advisable to provide a bug report to the providers of the problem library. Forcing the use of a particular map implementation (at first glance) is a bad idea.

+2
source

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 acting process with try / catch and catch an exception when that happens.

0
source

You must not throw in a HashMap! Throw on the card!
If you really have a reason for your question, then you need to create a new HashMap in case Map is not an instance of the map.
But this is a bad idea.

0
source

If you always assume that it is a HashMap<String, String> , why not just do it?

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

If you need something more general that any Map will accept:

 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, in your example, there is no return type. I assumed that you wanted to put void .

0
source

All Articles