2

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
    }
}
zomega
  • 1,538
  • 8
  • 26

1 Answers1

3

Don't define a raw entry, type it too

for (Main.Entry<String, String> e : m.entrySet()) {
    String s = e.getValue();
}
azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    Yeah, or use `var` if you’re on Java10+ – dshelya Jan 09 '22 at 16:13
  • @azro This is not an answer to my question. My question is why this is necessary because the java compiler must know the generics parameters from the class definition. – zomega Jan 11 '22 at 12:34
  • @somega read https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it ? – azro Jan 11 '22 at 13:47