How do I address unchecked cast warnings?

后端 未结 23 1205
醉梦人生
醉梦人生 2020-11-22 03:06

Eclipse is giving me a warning of the following form:

Type safety: Unchecked cast from Object to HashMap

This is from a call to

23条回答
  •  死守一世寂寞
    2020-11-22 03:38

    Take this one, it's much faster than creating a new HashMap, if it's already one, but still secure, as each element is checked against it's type...

    @SuppressWarnings("unchecked")
    public static  HashMap toHashMap(Object input, Class key, Class value) {
           assert input instanceof Map : input;
    
           for (Map.Entry e : ((HashMap) input).entrySet()) {
               assert key.isAssignableFrom(e.getKey().getClass()) : "Map contains invalid keys";
               assert value.isAssignableFrom(e.getValue().getClass()) : "Map contains invalid values";
           }
    
           if (input instanceof HashMap)
               return (HashMap) input;
           return new HashMap((Map) input);
        }
    

提交回复
热议问题