javanested-generics

Java generics: why does this nested template fail?


I have a situation that could be summarized as follows:

interface Hello<T> {
};

interface World<T, U> {
    void apply(Hello<T> t, Hello<U> u);
}

Now let's say I'd like to call World.apply without caring about the nested types, so I tried the following:

Hello<?> hello = ...;
World<?, ?> world = ...;
world.apply(hello, hello);

But I get this obscure message:

java: incompatible types: Hello<capture#1 of ?> cannot be converted to Hello<capture#2 of ?>

What's wrong here? Is there a way to accomplish that, besides resorting to raw types?

Casting world to World<Object, Object> is a way, but is there anything better?


Solution

  • ? means that it's unclear what a datatype is it actually. Unknown and unknown are incompatible to each other, because in fact it could be for instance Integer and String:

    Hello<?> hello = new HelloImpl<Integer>();
    World<?, ?> world = new WorldImpl<String,String>();
    

    Types are unknown in the compilation time.