日志文章

2019-12-19 aflfte2011

泛型的使用方法

package com.aflfte.collection;
/**
 * 泛型的使用方法
 * @author root
 *
 */
public class TestGeneric {
    public static void main(String[] args) {
        MyCollection<String> mc=new MyCollection<>();//泛型的使用方法:容器名称<内容的类型>,在这里定义好后下面设置和读取内容必须与设置的相同
        mc.set("张三", 0);
        //mc.set(888, 1);//由于上面设置了容器的内容类型为String所以888(int类型)就不可以存放在容器当中
        //Integer a=(Integer)mc.get(1);
        String b=mc.get(0);
    }
}
class MyCollection<E>{//<E>这里的E就是泛型标签,可用其它字母,用于定义容器内容的类型
    Object[] objs=new Object[5];
    public void set(E e,int index) {
        objs[index]=e;
    }
    public E get(int index) {
        return (E)objs[index];
    }
}

« Collection接口的使用方法 | 手动处理异常方法»