简体   繁体   中英

Java generic wildcard bounded in lists

I am trying to understand Java Generics and I'm puzzled by the bounded wildcards. I'm using the hierarchy from the Guidelines for Wildcard Use and have added a class PositiveEvenNumber inheriting from EvenNumber.

    List<? super EvenNumber> xn = new ArrayList<NaturalNumber>();
    xn.add(new NaturalNumber(35));  // compile-time error
    xn.add(new EvenNumber(-70));
    xn.add(new PositiveEvenNumber(70));
    xn.add(new Object());  // compile-time error

Why does the first line compile ? On second line, isn't NaturalNumber a parent of EvenNumber, why can't it be added ?

Thanks!

A List<? super EvenNumber> List<? super EvenNumber> is a list of some specific type, provided that that type is a supertype of EvenNumber .

Therefore, it might be a List<EvenNumber> , in which case you can't add a NaturalNumber .

This also means that you can't read anything from the list (except as Object ), since you don't know what type the list actually contains. (it could even be a List<Object> )

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