2

Why is the compiler not figuring out that i am using the wrong type in the snippet below?

Here's an interface with a generic.

interface Foo<X> {

    Map<String, String> getMap();

    X addFoos(int foos);

}

Notice the getMap() method which does not use X.

Why does this compile with just a warning?

void getMapFromFoo(Foo foo) {
    Map<Thread, java.util.GregorianCalendar> why = foo.getMap();
}

The any type for the map is accepted with just a warning about unsafe operation.

If however a wildcard is added, the compiler steps back in and only allows the right type.

void getMapFromFooWithWildcard(Foo<?> foo) {

    // Ok, as expected
    Map<String, String> map = foo.getMap();

    // This produces a syntax error, as expected
    Map<Thread, java.util.GregorianCalendar> ohWhy = foo.getMap();
}

What is going on?

Marco
  • 588
  • 1
  • 4
  • 15
  • 2
    When you use `Foo` as a raw type, you lose all generic aspects of it. See JLS Section 4.8: *"The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C. "* – aioobe Jul 13 '16 at 07:15
  • Interesting, thanks! – Marco Jul 13 '16 at 16:16

0 Answers0