Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java bounded generic type definition

Tags:

What's the difference between the following type definitions

<E extends Number> 

and

<? extends Number> 

Cheers, Don

like image 812
Dónal Avatar asked Dec 07 '08 21:12

Dónal


People also ask

What is a bounded generic type in Java?

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.

How do you declare a generic bounded type parameter 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).

What is bounded and unbounded wildcards in generics Java?

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.

What is generic data type in Java?

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.


1 Answers

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.

like image 163
Jon Skeet Avatar answered Oct 09 '22 22:10

Jon Skeet