java 泛型

1.泛型的定义

Java 泛型(generics)是 JDK 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型

public class Hello{

    // 泛型在返回类型之前
    public static <E> void printArray(E[] inputArray) {
        for (E element:inputArray) {
            System.out.printf("%s",element);        
        }
        System.out.println();
    }

    // 定义泛型
    public static <T> T printT (T name) {
        return name;
    }
    // 有界的类型参数
    public static <T extends Comparable<T>> T maxImun (T x, T y) {
        if (y.compareTo(x) > 0) {
            return y;
        } else {
            return x;
        }
    }

    public static void main(String[] args) {
        Integer[] intArray = {1,2,3,4,5};

        printArray(intArray);
        Integer x = 2;
        Integer y = 3;
        int c = 20;
        System.out.println(maxImun(x,c));
    }

}

2.泛型类

class Box<T> {
    private T t;

    public void add(T t){
        this.t = t;
    }

}

3.泛型通配符

class GenericTest {
    // 类型通配符
    public static void getData (List<?> data) {
        System.out.println(data.get(0));
    }

    // 类型通配符上界
    public static void getUperNumber (List<? extends Number> data){
        System.out.println(data.get(0));
    }
}
原文地址:https://www.cnblogs.com/myvic/p/8990220.html