【Java基础总结】泛型

泛型实现了参数化类型的概念,使代码可以应用于多种类型。

1. 泛型类

声明的泛型类型静态方法不能使用

class Tools<T>{
    private T t;
    public void set(T t){
        this.t = t;
    }
    public T get(){
        return this.t;
    }
}

2. 泛型方法

class GenericTest2<T>{
    //使用类定义的泛型
    public void print1(T t){
        System.out.println("print1:"+t);
    }
    //使用方法定义的泛型
    public <E> void print2(E e){
        System.out.println("print2:"+e);
    }
    //静态方法不能使用类定义的泛型
    public static <E> void print3(E e){
        System.out.println("print3:"+e);
    }
}

3. 泛型接口

//泛型接口
interface Inter<T>{
    void show(T t);
}
//
class InterImpl2 implements Inter<String>{
    public void show(String t)
    {
        System.out.println("show:"+t);
    }
    
}
//
class InterImpl<T> implements Inter<T>{
    public void show(T t){
        System.out.println("show:"+t);
    }
}
class GenericDemo5{
    public static void main(String[] args){
        InterImpl<Integer> i = new InterImpl<Integer>();
        i.show(5);
        //InterImpl i = new InterImpl();
        //i.show("liu");    
    }
}

4. 泛型限定

HashSet<? extends Person> set = new HashSet<? extends Person>();   //限定存储Person或Person子类的对象
HashSet<? super Person> set = new HashSet<? super Person>();   //限定存储Person或Person父类的对象
原文地址:https://www.cnblogs.com/lhat/p/6168895.html