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:
public class Box<T extends Number> { private T value; public Box(T value) { this.value = value; } public T getValue() { return value; } }
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.
Box<String> box = new Box<>("Hello World"); // 编译错误:String 不是 Number 的子类
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:
public class Box<T super Object> { private T value; public Box(T value) { this.value = value; } public T getValue() { return value; } }
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.
Box<Integer> box = new Box<>(123); // 编译错误:Integer 不是 Object 的超类
? to represent unknown types. For example, the following code shows a generic method
copy that copies the elements of one array to another array:
public static <T> void copy(List<? extends T> src, List<? super T> dest) { for (T t : src) { dest.add(t); } }
? 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!