This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Type safety: Unchecked casting

In my Spring application context file, I have something like this:

<util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="some_key" value="some value" />
    <entry key="some_key_2" value="some value" />   
</util:map>
Copy the code

In the Java class, the implementation looks like this:

private Map<String, String> someMap = new HashMap<String, String>();
someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
Copy the code

In Eclipse, I see a warning:

Type safety: Unchecked cast from Object to HashMap
Copy the code

Where did I go wrong? How can I solve the problem?

answer

Well, first of all, you’re wasting memory by creating a HashMap. Your second line completely ignores the reference to the hashMap you created, making it recyclable by the garbage collector. So instead of doing this, use:

private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
Copy the code

Second, the compiler warns you to cast the object to HashMap without checking whether it is a HashMap. But even if you do:

if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}

Copy the code

You may still receive this warning. The problem is that getBean returns Object, so the type is unknown. Converting it directly to a HashMap in the second case doesn’t cause a problem (and probably doesn’t issue a warning in the first case, and I’m not sure how rigorous the Java compiler’s mechanism for issuing warnings in Java 5 is). However, you are converting it to HashMap<String, String>. A HashMaps is actually a mapping of an Object as a key and another Object as a value (if you’re going to use HashMap<Object, Object>). Therefore, there is no guarantee that you can represent the bean as HashMap<String, String> when you get it, because you might get a HashMap<Date, Calendar> (because the returned non-generic representation can have any object).

If the code compiles and you can do String value = map.get(“thisString”); If there are no errors, you don’t have to worry about this warning. However, if the map does not consist entirely of string key-value pairs, a ClassCastException will occur at run time, because generics cannot prevent this from happening.

The article translated from Stack Overflow:stackoverflow.com/questions/2…