Java泛型

转载:http://www.cnblogs.com/lwbqqyumidi/p/3837629.html

http://www.weixueyuan.net/view/6321.html

http://www.weixueyuan.net/view/6323.html

http://blog.csdn.net/mtawaken/article/details/9813581

 

总结:

1. 泛型接口,泛型类,泛型方法

2. 通配符(?),泛型数组等

 

对泛型接口,example如下:

public interface Info<T> {
    public T getValue();
}
public class InfoImpl<T> implements Info<T> {
    
    private T value;

    public InfoImpl(T value) {
        // TODO Auto-generated constructor stub
        this.value = value;
    }
    
    @Override
    public T getValue() {
        // TODO Auto-generated method stub
        return value;
    }

}
public class Test {

    public static void main(String[] args) {
        Info<String> info = new InfoImpl<String>("chris");
        System.out.println(info.getValue());
    }
}

对泛型类,example如下:

public class NotePad<K,V> {
    private K k;
    private V v;
    
    public NotePad() {}
    
    public NotePad(K k, V v) {
        this.k = k;
        this.v = v;
    }
    
    public K getK() {
        return k;
    }
    public void setK(K k) {
        this.k = k;
    }
    public V getV() {
        return v;
    }
    public void setV(V v) {
        this.v = v;
    }
    
}
public static void main(String[] args) {
        NotePad<String, Integer> notePad = new NotePad<>("chen",30);
        System.out.println(notePad.getK()+"---"+notePad.getV());
        //
        NotePad<String, String> notePad2 = new NotePad<>("chen","chris");
        System.out.println(notePad.getK()+"---"+notePad2.getV());
        
    }

对泛型方法,example如下:

public class Base {
    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
    
}
public class Point<T1, T2> {

    private T1 t1;
    private T2 t2;
    
    public Point() {};
    
    public T1 getT1() {
        return t1;
    }
    public void setT1(T1 t1) {
        this.t1 = t1;
    }
    public T2 getT2() {
        return t2;
    }
    public void setT2(T2 t2) {
        this.t2 = t2;
    }    
}
public class Test {

    public static void main(String[] args) {
        Point<String, Integer> point = new Point<>();
        point.setT1("string");
        point.setT2(10);
        printPoint(point);

    }

    // one static method to test Generic Type
    // Generic Method
    public static <T1 extends Base, T2 extends Base> void printPoint(T1 x, T2 y) {
        System.out.println(x.getValue());
        System.out.println("-----------");
        System.out.println(y.getValue());
    }

    // another static method to test Generic Type
    // Generic Method
    public static void printPoint(Point<?, ?> point) {
        System.out.println(point.getT1());
        System.out.println("-----------");
        System.out.println(point.getT2());
    }
}

 

泛型:保证类型安全,且作用于编译阶段。

泛型擦除:指未使用泛型,尽管已经定义了泛型相关的类等。

 

posted on 2016-03-17 09:21  -赶鸭子上架-  阅读(212)  评论(0编辑  收藏  举报