A type argument for a parameterized type is not limited to a concrete class or interface. Java allows the use of type wildcards to serve as type arguments for parameterized types. Wildcards are type arguments in the form "?", possibly with an upper or lower bound. Given that the exact type represented by a wildcard is unknown, restrictions are placed on the type of methods that may be called on object of the parameterized type.
As an example of an unbounded wildcard, List>
indicates a list which has an unknown object type. Methods which take such a list as a parameter will accept any type of list as argument. Reading from the list will return objects of type Object
, and adding null elements to the list is not allowed, since the element type is not known.
To specify the upper bound of a type wildcard, the extends
keyword is used, which indicates that the type argument is a subtype of the bounding class. So List extends Number>
means that the given list contains objects of some unknown type which extends the Number
class. For example, the list could be List
or List
. Reading an element from the list will return a Number
, while adding null elements is once again not allowed.
The use of wildcards above adds flexibility since there is not any inheritance relationship between any two parameterized types with concrete type as type argument. Neither List
nor List
is a subtype of the other, even though Integer
is a subtype of Number
. So, any method that takes List
as parameter does not accept an argument of List
. If it did, it would be possible to insert a Number
that is not an Integer
into it, which violates type safety. Here is sample code that explains the contradiction it brings if List
were a subtype of List
:
The solution with wildcards works because it disallows operations that would violate type safety.
List extends Number> nums = ints; // it is OK nums.add(3.14); // it is prohibitedTo specify the lower bounding class of a type wildcard, the super
keyword is used. This keyword indicates that the aforementioned parameterized type is with a type argument which is a super-type of said bounding type. So, List super Number>
could represent List
or List
. Reading from a list defined as List super Number>
returns elements of type Object
. Adding to such a list requires elements of type Number
or any super-type of Number
.
Read more about this topic: Generics In Java
Famous quotes containing the word type:
“The more characteristic American hero in the earlier day, and the more beloved type at all times, was not the hustler but the whittler.”
—Mark Sullivan (18741952)