If A extends X, the following declaration is valid
List<? extends X> list = new ArrayList<A>();
It seems to be that a list would hold a collection of elements that extend X. As such, new A() should qualify.
Yes, it does not. Why is that?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’ve almost got it.
List<? extends X>means “a list of some type (which I don’t actually know) which is a subtype of X (or possibly X itself)”.The problem is if X is, for example,
Number. ThenList<? extends X>meansList<Double>orList<Integer>or some other type, which you’ve just said you don’t actually know. You can’t insert anyNumberinto aList<Integer>. So, since you don’t know the type of the elements of the list, you can’t insert anything into aList<? extends Number>. You can, however, retrieve values from the list, and you are guaranteed that any value contained in the list is at least aNumber.For more information, read Item 28: Use bounded wildcards to increase API flexibility in Effective Java, 2nd Ed. by Joshua Bloch (a book which every Java programmer should have on their bookshelf). In particular, this item explains the mnemonic PECS, meaning “producer extends, consumer super”, which will help you remember what the
extendsandsuperkeywords mean in Java generics and when they should be used.