Why does HashMap.Entry not take generics parameters of its parent?

Viewed 43

I have an object of type HashMap<String, String>. But HashMap.Entry.getValue() still returns object. It does not respect the generics parameters of it's parent HashMap. The same applies to getKey().

Here is the example:

class Main extends HashMap<String, String>
{
    public static void main(String[] args)
    {
        Main m = new Main();
        m.put("key", "value");
    
        for (Main.Entry e : m.entrySet())
            String s = e.getValue(); // this line throws an error telling that getValue() returns Object and not String
    }
}
1 Answers

Don't define a raw entry, type it too

for (Main.Entry<String, String> e : m.entrySet()) {
    String s = e.getValue();
}
Related