The upper bound of a generic specifies that the type parameter must be a subclass of a certain class or implement a certain interface. Its syntax is T extends B
, where T is the generic type parameter and B is the upper bound type. For example, the following code shows a generic class Box
, whose type parameter T must be Number
or its subclass:
1 2 3 4 5 6 7 8 9 |
|
In the above code , we used the extends
keyword to specify the upper bound type of the generic type parameter, which means that the generic type parameter must be Number
or its subclass. In this way, we can use the Box
class to store values of types Integer
, Double
, Float
, etc., because they are all ## A subclass of #Number. In addition, by using the upper bound of generics, we can ensure that only values of type
Number are stored in instances of the
Box class, avoiding the risk of type conversion exceptions.
1 |
|
T super B, where T is the generic type parameter and B is the lower bound type. Here is an example showing a generic class
Box whose type parameter T must be
Object or its superclass:
1 2 3 4 5 6 7 8 9 |
|
super keyword to specify the lower bound type of the generic type parameter, which means that the generic type parameter must be
Object or its superclass. In this way, we can use the
Box class to store
Object,
String,
Integer,
Double, etc. value because they are all subclasses of
Object. In addition, by using the lower bound of generics, we can ensure that the values stored in instances of the
Box class are all of the
Object type, avoiding the risk of type conversion exceptions.
1 |
|
? to represent unknown types. For example, the following code shows a generic method
copy that copies the elements of one array to another array:
1 2 3 4 5 |
|
? to represent an unknown type, it can satisfy both
src parameter is
T type or its subclass,
dest parameter is
T Constraints on types or their superclasses. This way, we can copy elements of any type into another list. By using upper and lower bound wildcards, we can define generic methods more flexibly while ensuring type safety.
The above is the detailed content of How to use upper and lower bound wildcards for Java generics. For more information, please follow other related articles on the PHP Chinese website!