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);
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.
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);
}
}
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.
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.
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.
Related
I am trying to cast an Object to HashMap<String, Object> in a neat, robust way. So far, every way I tried produces compiler warnings or errors. What is the proper way to do it? I have checked the internet and tried the following:
HashMap<String, Object> map = (HashMap<String, Object>) object;
The code above gives an unchecked conversion warning.
HashMap<String, Object> map = new HashMap<>();
if (object instanceof Map<String, Object>){
map = (Map<String, Object>) object;
}
The code above gives an error, which says that objects cannot be compared to parameterized collections.
HashMap<String, Object> map = new HashMap<>();
if (object instanceof Map){
Map genericMap = (Map) object;
for (Object key : genericMap.keySet()){
if (key instanceof String){
map.put((String) key, genericMap.get(key));
}
else{
throw new KeyException();
}
}
}
The code above yields a warning that "Map is a raw type. References to generic type Map<K,V> should be parameterized."
So what would be the proper way to do this? Thank you in advance!
I am trying to cast an Object to HashMap<String, Object> in a neat, robust way. So far, every way I tried produces compiler warnings or errors. What is the proper way to do it?
There is no proper way to do it, supposing that "proper" implies both useful and type safe. Casting is the antithesis of type safety. Other than casts for arithmetic purposes, a safe cast is an unnecessary one.
There is not enough information to determine how to achieve what ultimately you are after, but generally speaking, that sort of thing revolves around writing true generic code instead of using type Object to funnel objects of unrelated type into the same methods, using instanceof to determine what you actually have, or casting.
Just add #SuppressWarnings("unchecked") to your method
#SuppressWarnings("unchecked")
public void myMethod(){
...
}
and you should be able to use
HashMap<String, Object> map = (HashMap<String, Object>) object;
Below is my code snippet
Map<Object, Object> gobalMap = new HashMap<Object, Object>();
Map<String, Map<String, Integer>> mp = new HashMap<String, Map<String, Integer>>();
gobalMap.put("mp",mp );
((Map<String, Map<String, Integer>>)gobalMap.get("mp")).put("A", new HashMap<String, Integer>().put("A", 1));
error:
The method put(String, Map<String,Integer>) in the type Map<String,Map<String,Integer>> is not applicable for the arguments (String, Integer)
May I know where am doing wrong ..?
new HashMap<String, Integer>().put("A", 1)
This returns an Integer. But you want to add this to an object which stores Maps and not Integer. So that's not possible. Also as Thomas explained in the comments, your code would not work even if it compiled because put returns the previous value of the map so you will receive a NullPointerException.
I would recommend restructuring your code to make it more readable and to also make it work:
Map<Object, Object> gobalMap = new HashMap<Object, Object>();
Map<String, Map<String, Integer>> mp = new HashMap<String, Map<String, Integer>>();
gobalMap.put("mp",mp );
HashMap<String, Integer> aMap = new HashMap<>();
aMap.put("A", 1);
((Map<String, Map<String, Integer>>)gobalMap.get("mp")).put("A", aMap);
As others have already stated new HashMap<String, Integer>().put("A", 1) returns an Integer (the previously mapped value for key "A" so null in this case) and that is not a suitable value for a Map<String, Map<String, Integer>>.
You're creating a suitable map but don't actually put it into the map so the reference to that map is lost.
Since you're probably trying to only create a nested map if it doesn't exist already try this:
((Map<String, Map<String, Integer>>)gobalMap.get("mp"))
.computeIfAbsent( "A", k -> new HashMap<String, Integer>())
.put("A", 1);
This does the following:
get and cast the map from globalMap (if you'd not be sure this can't return null you could use computeIfAbsent() here as well)
get the nested map for key "A" and if it doesn't exist create a new one, add and return it
put the value 1 for key "A" into the nested map
new HashMap<String, Integer>().put("A", 1) returns an integer, because when you put into a hashmap, you get back the previous value held by that key. As such it cannot be the value in a Map<String,Map<String,Integer>>.
Perhaps you meant to cast gobalMap to a Map<String,Map<String,Integer>>. But you are actually casting gobalMap.get("mp") to a Map<String, Map<String, Integer>>.
This, on the other hand, would compile:
((Map<String, Integer>) gobalMap.get("mp")).put("A", new HashMap<String, Integer>().put("A", 1));
though I'm not sure it does anything useful.
you missed the bracket. correct code will be:
((Map<String, Map<String, Integer>>)gobalMap.get("mp")).put("A", new HashMap<String, Integer>()).put("A", 1);
I need to convert raw Map to Map<string,string>, and I think I have to first convert the raw map to Map<Object,Object> and then convert it again to Map<String,String>.
code snippet goes like below.
Map obj1 = new HashMap();
obj1.put("key1", 1);
obj1.put("key2", false);
obj1.put("key3", 3.94f);
Map<Object, Object> obj2 = obj1;
Map<String, String> obj = new HashMap<String,String>();
for (Map.Entry<Object, Object> entry: obj2.entrySet()) {
obj.put(entry.getKey().toString(), entry.getValue().toString());
}
I guess it would work in any condition but I want to hear from others about possible danger of this code.(any possiblities for ClassCastException for example?)
Please also let me know if you have a better idea.
-- revised code
Map obj1 = new HashMap();
obj1.put(2, 1);
obj1.put(true, false);
obj1.put(4.4f, 3.94f);
Map<String, String> obj = new HashMap<String,String>();
for (Object k : obj1.keySet()){
obj.put(k.toString(), obj1.get(k).toString());
}
Since raw Map entries will contain key/value of Objects anyway, I think I don't need temporary Map<Object,Object>. Just iterating over each item works well and I don't see any issues so far.
If You Look out the Definition of HashMap in jdk 1.4 It was earlier Implements using Object Class when generics Concept not came.
When generics is Introduced this object is Replaced with <T>. But If you Still don't use Generics Type Safe then Internally this Statement new HashMap() reflects a instance of <Object, Object>. Better To use directly a
a new HashMap() is better idea. There should no need of Map <Object, Object> obj2.
So, GO For this.. a better approach.
Map obj1 = new HashMap();
obj1.put("key1", 1);
obj1.put("key2", false);
obj1.put("key3", 3.94f);
Map<Object, Object> obj2 = obj1;
Map<String, String> obj = new HashMap<String,String>();
for (Object obj_Entry : obj1.entrySet()) {
Map.Entry entry = (Map.Entry) obj_Entry; // This will Work Fine all Time.
obj.put(entry.getKey().toString(), entry.getValue().toString());
}
Your code will not generate ClassCastExceptions. Actually you are not doing any casting here. You just call the toString() method of every key/value pair to make it a string. As long as toString() returns a valid value of your objects. Your code will be fine.
But your code may produce NullPointerExceptions if your obj1 contain null keys or objects
obj1.put(null, "null value")
Also note that some key collisions may occur if toString() methods return same String value for two keys. This is unlikely but it is possible.
I have map of maps
Map<String, Map<String,Integer>> outerMap = new HashMap<String, Map<String, Integer>>();
and I want to put some values to inner map. Is that correct way? Or it can be done better?
class SampleMap {
Map<String, Map<String, Integer>> outerMap = new HashMap<String, Map<String, Integer>>();
public void add(String outerKey, String innerKey, Integer value) {
Map<String, Integer> tempMap = new HashMap<String, Integer>();
if (outerMap.size() > 0)
tempMap = outerMap.get(outerKey);
tempMap.put(innerKey, value);
outerMap.put(key, tempMap);
}
}
You can improve the code by avoiding the creation of a new inner map eagerly, until the point when you know that you must create it.
In addition, if you know that the inner map instance came from the outer map, you don't have to spend time putting it back where it came from.
public void add(String outerKey, String innerKey, Integer value) {
Map<String, Integer> tempMap
if (outerMap.containsKey(outerKey)) {
tempMap = outerMap.get(outerKey);
} else {
tempMap = new HashMap<String, Integer>();
outerMap.put(outerKey, tempMap);
}
tempMap.put(innerKey, value);
}
Technically there is nothing wrong in your code (except a minor improvement suggested by dasblinkenlight), but is map of maps what you really need?
If you want to read/write values by two keys, probably it's better to create map from pair of two keys (MultiKey or Pair implementation can be used) or another data structure (see this comment for details https://stackoverflow.com/a/3093993/554281)
Why isn't a Map<String,List<SomeBean>> castable to Map<String,List<?>>?
What I'm doing now is this:
Map<String, List<SomeBean>> fromMap = new LinkedHashMap<String, List<SomeBean>>();
/* filling in data to fromMap here */
Map<String,List<?>> toMap = new LinkedHashMap<String, List<?>>();
for (String key : fromMap.keySet()) {
toMap.put(key, fromMap.get(key));
}
In my opinion there should be a way around this manual transformation, but I can't figure out how. Any Ideas?
The cast is invalid because in Map<String,List<?>> you can put List<String> and List<WhatEver>, but not in Map<String, List<SomeBean>>.
For instance:
//List<SomeBean> are ok in both lists
fromMap.put("key", new ArrayList<SomeBean>());
toMap.put("key", new ArrayList<SomeBean>());
//List<String> are ok in Map<String,List<?>>, not in Map<String, List<SomeBean>>
fromMap.put("key", new ArrayList<String>()); //DOES NOT COMPILE
toMap.put("key", new ArrayList<String>());
To simplify your code, you may use the appropriate constructor to simplify your code:
Map<String, List<SomeBean>> fromMap = new LinkedHashMap<String, List<SomeBean>>();
Map<String,List<?>> toMap = new LinkedHashMap<String, List<?>>(fromMap);
Not realy an answer to your question, but as an extra: I would not use keyset here... If you want to iterate through all the elements of a map, use the entrySet() method. Its faster because it does not require the key-value lookup for each element.
for (Map.Entry<String, List<SomeBean>> entry : fromMap.entrySet()) {
toMap.put(entry.getKey(), entry.getValue());
}
If you really want to, you could cast to a raw Map (but what you want is not type safe):
Map<String,List<?>> toMap = (Map) new LinkedHashMap<String, List<String>>();
When assigning to a Map, where K and V are not wildcard parameters, the Map being assigned must have exactly the same K and V. In your case, V must be exactly List<?>.
The workaround it to use a wildcard V.
Map<String, ? extends List<?>> map = new LinkedHashMap<String, List<String>>();
Because the V you are assigning to is a wildcard, the V being assigned must only be assignable to V (rather than being exactly V).