Defined type variable
Sometimes, class or method need to be constraints on the type of the variable. Here is a typical example, we are looking for the smallest element in the array:
public class ArrayAlg {
public static <T extends Comparable> T min(T[] array){
if (array == null || array.length == 0){
return null;
}
T smallest = array[0];
for (int i=0;i<array.length;i++){
if (smallest.compareTo(array[i])>0){
smallest = array[i];
}
}
return smallest;
}
}
In the above code
note
A plurality of defined types of variables can have, for example:
<T extends Comparable & Serializable , U extends Comparable>
Type defined using the "&" to separate, while "," for the partition type parameter.
In Java, a class can implement multiple interfaces, but only one parent, so the type defined parameters, there may be a plurality of interfaces, but only one class.
<T extends 接口1 & 接口2 & ... & 接口n & 类型1>