Java泛型

1.泛型也可以应用于接口。生成器是专门负责创建对象类,在生成器中只定义一个方法,用来产生新的对象。

public class Test17 {
    public static void main(String[] args) {
        B2 b = new B2();
        b.a("hello");
    }
}

interface A2<T> {
    public void a(T t);
}

class B2<T> implements A2<T> {

    @Override
    public void a(T t) {
        System.out.println(t.toString());
    }
}

class C2 implements A2<String> {

    @Override
    public void a(String t) {
        System.out.println(t.toString());
    }
}

2.泛型方法:要定义泛型方法,只需将泛型参数列表置于返回值前。相比泛型类,优先使用泛型方法。static方法无法访问泛型类类型参数,只能使用泛型方法。当使用泛型类时,必须在创建对象的时候指定类型参数的值。而使用泛型方法的时候,通常不必指定参数类型,因为编译器会找出具体类型,这称为类型参数推断。

class Man {
}

public class Test18 {
    public <T> T t(Class<T> c) throws InstantiationException, IllegalAccessException {
        T t = c.newInstance();
        return t;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Test18 t1 = new Test18();
        Object o = t1.t(Man.class);
        System.out.println(o);
    }
}

3.RandomList:作为容器的的另一个例子,我们需要一个持有特定类型对象的列表,每次调用其上的select()方法时,可以随机地选取一个元素。

public class Test19<T> {
    private ArrayList<T> a = new ArrayList<T>();
    private Random r = new Random(47);

    public void add(T t) {
        a.add(t);
    }

    public T select() {
        return a.get(r.nextInt(a.size()));
    }

    public static void main(String[] args) {
        Test19<String> rs = new Test19<String>();
        for (String s : ("Hello World " + "Hello Java").split(" ")) rs.add(s);
        for (int i = 0; i < 11; i++)
            System.out.print(rs.select() + " ");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值