Limited Java files do not compile

I cannot collect this, and I see no reason. Ultimately, I want to pass a collection of objects whose class extends TClass in the generate method, which accepts a collection of objects whose class extends TClass, This should work.

Any help would be greatly appreciated.

public interface Generator<IT extends ITClass, T extends TClass> { IT generate(Collection<T> tClassCollection) } Generator<?, ? extends TClass> generator = generatorClass.newInstance(); Collection<? extends TClass> TClassCollection = ... 

... generator.generate(TClassCollection);

I get this error

 The method generate(Collection&lt;capture#8-of ? extends TClass>) in the type Generator&lt;capture#7-of ?,capture#8-of ? extends TClass> is not applicable for the arguments (Collection&lt;capture#9-of ? extends TClass>) 
+1
source share
2 answers

This should work

Not; he could open a loophole in the type system if that were to happen. Consider:

 class SpecialT extends TClass {} class SpecialGenerator extends Generator<ITClass, SpecialT> {} Generator<?, ? extends TClass> generator = SpecialGenerator.class.newInstance(); Collection<? extends TClass> TClassCollection = Arrays.asList(new TClass()); generator.generate(TClassCollection); 

A SpecialGenerator can only work with Collection<SpecialT> , but you are trying to pass a Collection<TClass> that can contain instances of types other than SpecialT .

+1
source

The wildcard in the general declaration does not mean "any type"; it means "some unknown type."

So, if you have a Generator<?, ? extends TClass> Generator<?, ? extends TClass> , this does not mean that you can pass its generate() method to any Collection if it contains a TClass subtype.

On the contrary, this means that you cannot call the generate() method with a safe type, because you do not know the type of elements that it can accept.

+1
source

Source: https://habr.com/ru/post/1498113/


All Articles