Benjamin Bettan
Benjamin Bettan

Reputation: 91

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 !

Upvotes: 3

Views: 5954

Answers (2)

Neil
Neil

Reputation: 5782

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.

Upvotes: 5

Mark Peters
Mark Peters

Reputation: 81074

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()) {

Upvotes: 6

Related Questions