Java基础篇(泛型<T>常见用法)

来源:互联网 发布:丧尸围城2优化补丁 编辑:程序博客网 时间:2024/06/07 03:54
//单泛型class Test1<T> {    T t;    public Test1(T t) {        this.t = t;    }    void sys() {        System.out.println("a= " + t);    }}// 多泛型class Test2<M, R> {    M m2;    R r2;    public Test2(M m2, R r2) {        this.m2 = m2;        this.r2 = r2;    }    public void sys() {        System.out.println("姓名: " + m2 + "  年龄   " + r2);    }}// 泛型嵌套class Info<A, B> {    private A name;    private B age;    public Info(A name, B age) {        this.name = name;        this.age = age;    }    public A getName() {        return name;    }    public B getAge() {        return age;    }}class List<L> {    public L item;    public List(L item) {        this.item = item;    }    public L getItem() {        return item;    }}public class Fan {    public static void main(String args[]) {        // 最基本的泛型        Test1<String> t1 = new Test1<String>("Hello");        t1.sys();        // int会报错,应该用Integer包装类        Test2<String, Integer> t2 = new Test2<String, Integer>("张三", 11);        t2.sys();        // 嵌套的泛型        Info<String, Integer> info = null;        List<Info<String, Integer>> list = null;        info = new Info<String, Integer>("李四", 12);        list = new List<Info<String, Integer>>(info);        System.out.println("姓名  " + list.getItem().getName());        System.out.println("年龄  " + list.getItem().getAge());        // 通过泛型方法返回泛型类        Test1<String> t11 = fun("World");        t11.sys();    }    // <T> 返回的泛型类的类型    // Test1<T>泛型类    // T para 泛型参数    // 三个泛型必须一致    public static <T> Test1<T> fun(T para) {        Test1<T> temp = new Test1<T>(para);        return temp;    }}

运行结果如下
这里写图片描述

0 0