What's the difference between the following type definitions
<E extends Number>
and
<? extends Number>
Cheers, Don
If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
both bounded and unbounded wildcards provide a lot of flexibility on API design especially because Generics is not covariant and List<String> can not be used in place of List<Object>. Bounded wildcards allow you to write methods that can operate on Collection of Type as well as Collection of Type subclasses.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
This version:
<? extends Number>
can appear in a non-generic method/type, and it basically means "I don't care what the type is, so long as it derives from Number
. I'm not going to really use the type, I just need it to be appropriate."
This version:
<E extends Number>
requires E to be a type parameter. It allows you to do more (for instance, creating an ArrayList<E>
later on) but the extra type parameter can make things more complicated when you don't really need them to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With