Generic 泛型

参考 http://tutorials.jenkov.com/java-generics/methods.html


定义使用泛型的类

public class GenericFactory<E> {
    Class theClass = null;

    public GenericFactory(Class aClass){
        this.theClass = aClass;
    }

    public E createInstance() throws IllegalAccessException, InstantiationException {
        return (E)theClass.newInstance();
    }
}

定义使用泛型的方法

    private static <T> T addAndReturn(T element,Collection<T> collection){
        collection.add(element);
        return element;
    }

在类声明和方法声明时,用<T>(<>中字符任意)声明一个“泛型类型”

    private static <T> T getInstance(Class<T> aClass) throws IllegalAccessException, InstantiationException {
        return aClass.newInstance();
    }


泛型通配符(wildcards)

List<?>           listUknown = new ArrayList<A>();
List<? extends A> listUknown = new ArrayList<A>();
List<? super   A> listUknown = new ArrayList<A>();
List<?>  means a list typed to an unknown type. 

List<? extends A> means a List of objects that are instances of the class A, or subclasses of A (e.g. B and C).

List<? super A> means that the list is typed to either the A class, or a superclass of A.

    public void processElements(List<?> elements){
        for(Object obj : elements){
            //do something
        }
    }

    public void processElements(List<? extends A> elements){
        for(A a : elements){
            System.out.println(a.getValue());
        }
    }

    public void processElements(List<? super A> elements){
        for(Object a : elements){
            //do something
        }
    }



为什么使用泛型?

1,不需要类型强转,因为编译器已做过类型检查

2,使用泛型后,对Collection就可以使用for-each循环了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值