Home Ask Login Register

Developers Planet

Your answer is one click away!

Benjamin Bettan February 2016

Java - Unchecked cast from Object to Map.Entry<String,String>

I have an "unchecked cast from Object to Map.Entry" on "Map.Entry entry = (Entry) o;"

I think everything is OK and I can put an add suppress warning safely but I'm not sure. Here's my code.

public abstract class WebPath {
    protected Hashtable<String, String> wp;

    public String get(String whatDoYouWant) {
        for (Object o : wp.entrySet()) {

            Map.Entry<String, String> entry = (Entry<String, String>) o;
            if (whatDoYouWant.equals(entry.getKey())) {
                return (String) entry.getValue();

        return null;

Thank you everybody, have a good day !


Mark Peters February 2016

Don't suppress the warning, it's giving you good advice! You are choosing to assign each entry to the uninformative base class Object, instead of the more precise type, Map.Entry<String, String>. If you fix your for-loop you will eliminate the warning:

for(Map.Entry<String, String> o : wp.entrySet()) {

Neil February 2016

The compiler doesn't like it when you take an instance and cast it to a derived class. This is because you have no guarantee that that instance is that derived class. If you know better such as in your case, that's fine, but it is not best practice in general.

Your wp.entrySet() is returning a Set of Map.Entry. So use Map.Entry! Better still if you're not dropping the generic types, so you should have:

for(Map.Entry<String, String> entry : wp.entrySet()) {
    // ...

No need to cast it since you know what type it is.

Post Status

Asked in February 2016
Viewed 2,471 times
Voted 6
Answered 2 times


Leave an answer

Quote of the day: live life