Generic Java defined variables

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 Examples of the types of limits for types of parameters T, must implement the Comparable interface (containing only standard interface compareTo method) of the class. If there is no limit on the T, so not sure the type instantiated T has compareTo method.

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>

Guess you like

Origin www.cnblogs.com/KenBaiCaiDeMiao/p/12638644.html