简体   繁体   中英

Why doesn't this generic assignment work?

I have a method like so:

<T extends ImportedGroupTxtContact> Importer<T> createImporter(Class<T> classToImport) 

In the method body this is fine:

ParseResult<? extends ImportedGroupTxtContact, ?> parseResult = new ParseResult<ImportedGroupTxtContact, ChildContactField<?>>();

Yet this is not:

ParseResult<T, ?> parseResult = new ParseResult<ImportedGroupTxtContact, ChildContactField<?>>();

This makes no sense to me, as T extends ImportedGroupTxtContact has the same upper bound as ? extends ImportedGroupTxtContact ? extends ImportedGroupTxtContact . What exactly is wrong?

T extends ImportedGroupTxtContact . So it could be any subclass of ImportedGroupTxtContact . Let's replace that with Fruit . Apple extends Fruit. But you can't do

Basket<Apple> basket = new Basket<Fruit>();

Indeed, a Basket<Apple> only accepts apples, whereas a Basket<Fruit> accepts any kind of Fruit.

You are assigning a ParseResult<A, B> to ParseResult<T, ?> where T may or may not be equal to A , so this must fail. More precisely, T can be any subtype of A . The fact that T and the ? from your first example both have the same upper bound doesn't enter the equation here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM