Home > Software engineering >  Java: cast Object to HashMap<String, Object>
Java: cast Object to HashMap<String, Object>

Time:11-02

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!

CodePudding user response:

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.

CodePudding user response:

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;
  • Related