Why am I getting an unchecked cast warning in Java?

In my Spring application context, I define a map 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>

Then, in my Java class:

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

Eclipse shows a warning: Type safety: Unchecked cast from Object to HashMap<String, String>.

What causes this unchecked cast java issue, and how can I fix it?

I’ve been working with Java for over a decade now, and yeah, this one comes up pretty often. If you’re getting an unchecked cast java warning and you’re absolutely sure about the type (like Map<String, String>), you can go ahead and suppress it safely using:

@SuppressWarnings("unchecked")
private Map<String, String> someMap = (HashMap<String, String>) getApplicationContext().getBean("someMap");

:white_check_mark: Why?

This approach silences the warning while trusting your own config. Just don’t forget—it’s safe only if you’re 100% confident about that bean type.

Totally agree with @joe-elmoufak —and I’ve run into this too after switching between multiple Spring projects. But one small improvement I’d suggest: go with the interface type instead of the concrete implementation. It’s cleaner and avoids unnecessary casting, which helps with that same unchecked cast java issue.

private Map<String, String> someMap = (Map<String, String>) getApplicationContext().getBean("someMap");

:white_check_mark: Why?

You’re keeping it generic (which Spring returns anyway), and you still maintain type safety without tying yourself down to a HashMap.

Use ApplicationContext#getBean with Generics (Best Practice) Spring supports generic type inference with this method: private Map<String, String> someMap = getApplicationContext().getBean(“someMap”, Map.class);

:white_check_mark: Why?

Eliminates unchecked cast warnings without suppression.