Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

super and extends in generic types of an ArrayList

Hi Frederick!

Btw,


     * List<? extends Number> ml=new Vector<Integer>();
     * List<? extends Number> ml=new Vector<Double>();
     * List<? extends Number> ml=new Vector<Short>(); - // won't compile in jdk 7. 


I don't know - it is valid answer ONLY for jdk 6?

As from jdk 7 (I don't know about jdk 6) and according to https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html -

"Box<Integer> is not a subtype of Box<Number> even though Integer is a subtype of Number"- it is bad question and should be removed from the exam, I guess

I stand that there's nothing wrong with this question.


In fact, all three lines you added works independently with all versions from JDK 5 to JDK 8.


It's true that you can't assign a <Integer> generic type to a reference with <Number> generic type. However, the part where it says <? extends Number> makes that possible. In simple words, when it says "? extends Number" it reads as "accept anything that is either Number of a subclass of it".


However, this question is not about whether you can compile these lines independently - it's about what objects you can pass to the .add(-) method of the given list, which is strongly influenced by the generic type you use in the reference type.


For a clearer understanding of how generics work from the top, why not watch our generics video?

http://www.examlab.org/v/java-generics


It gives you a complete understanding of generics from the beginning!

Thank you for the useful explanation! I got confused a bit - yes, you are right, "? extends ..." makes this code compiling.

Also now I realized this question is about PECS principle, PECS stands for Producer-Extends-Consumer-Super.

Also you cannot add anything to a Collection<? extends Number>, because you cannot know at runtime which specific subtype of Number the collection holds.

Collection<? super Integer> can always hold an Integer no matter what the actual parameterized type is. Here you don't care what is already in the list as long as it will allow a Integerto be added;

You nailed it!

I wish you had joined our course, in which case I would have been able to make a great boost of the score and accuracy in your score predictor :)

Thank for the great link!

ExamLab © 2008 - 2024