Reputation: 303
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!
Upvotes: 1
Views: 2527
Reputation: 1
Below is the above code written such that you don't need @SuppressWarnings to compile cleanly. You can read up on "Unbounded Wildcards" to understand their proper use better. Java docs state they can be used when:
I think both of these apply to your situation.
Code written with unbounded wildcards "?":
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();
}
}
}
Edited for clarity
Upvotes: 0
Reputation: 181859
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.
Upvotes: 5
Reputation: 323
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;
Upvotes: 0