Here you ask three questions, I will answer them separately. By the way, it would be useful for you to read the Java Generics Frequently Asked Questions - many of which were canonical links to the topic :
- So what is the point of using the wildcard character
<? extends Number> <? extends Number> ?
You need to use a wildcard for the time when the parameterized argument is a subclass of Number , say Integer . For instance:
import java.util.LinkedList; import java.util.List; public class NumberTest { public static void main(String... args) { List<Integer> newList = new LinkedList<Integer>(); organizeData(newList);
The second method call fails with a compilation error:
NumberTest.java:9: error: method anotherMethod in class NumberTest cannot be applied to given types; anotherMethod(newList);
- Why am I getting an element of type
Object from c ? And not of type Number ?
The reason you get the Object type in the second case is because you are using the Raw Type. You should never use a raw type, if you can avoid it for this reason - you lose all the benefits of compiler type checking.
- Is there a way to allow passing only subtypes of type as arguments, and not allow non-parameterized arguments?
You cannot interfere with Heap Pollution in the way you describe, because someone can always be classified as Raw, and then what is required. Generics is a compilation of time, only a design, and ultimately erased after compilation. That is why the Unchecked Type Conversion warning can only be suppressed through annotation.
source share