15 泛型

1.泛型类

public class Holder {
    T a;
    public Holder(T a) {
        this.a = a;
    }
    public static void main(String[] args) {
        new Holder(new Circle());///只能存入Shape或者是其子类
        /////new Holder(new Shape());  编译错误
    }
}

class Shape{
    void fun(){
        System.out.println("Shape");
    }
}

class Circle extends Shape{
    @Override
    void fun() {
        System.out.println("Circle");
    }
}

2.泛型方法

public class GenericMethod {
    
    public  T f(T x){
        return x;
    }
    
    public  String v(T x){
        return x.getClass().getName();
    }
    
    public  List asList(T... args) {
        List list = new ArrayList<>();
        for(T t:args){
            list.add(t);
        }
        return list;
    }
    
    public static void main(String[] args) {
        GenericMethod g = new GenericMethod();
        
        g.f("fuck"); //////自动类型推断,自动推断只会发生在赋值操作
        
        g.f("you");  /////显式类型说明,一般不用
        
        List list = g.asList("I fuck you".split(" ")); ////可变参数与泛型方法
        System.out.println(list);
        
        System.out.println(g.v(1));
    }
}

3.擦除

你可能感兴趣的:(15 泛型)