86.自定义泛型

    技术2022-07-11  92

    不使用泛型
    package test; /* * 测试 * */ public class testGeneric { public static void main(String[] args) { myCollection mc = new myCollection(); mc.set("硕鼠", 0); mc.set(998, 1); Integer a = (Integer)mc.get(1); //需要强制类型转换 String b = (String)mc.get(0); System.out.println(a); System.out.println(b); } } class myCollection{ Object[] objs = new Object[5]; public void set(Object obj, int index) { objs[index] = obj; } public Object get(int index) { return objs[index]; } }
    泛型类的声明
    class myCollection<E>{ Object[] es = new Object[5]; public void set(E e, int index) { es[index] = e; } public E get(int index) { return (E)es[index]; } }

    我们可以在类的声明处增加泛型列表,如:<T,E,V>。

    此处,字符可以是任何标识符,一般采用这3个字母。

    泛型类的应用
    package cn.yzy.collection; /* * 测试泛型 * */ public class testGeneric01 { public static void main(String[] args) { myCollection<String> mc = new myCollection<String>(); mc.set("硕鼠", 0); mc.set("硕喵", 1); String a = mc.get(1); //加了泛型,直接返回String类型,不用强制转换; String b = mc.get(0); System.out.println(a); System.out.println(b); } } class myCollection<E>{ Object[] es = new Object[5]; public void set(E e, int index) { es[index] = e; } public E get(int index) { return (E)es[index]; } }
    Processed: 0.012, SQL: 9