泛型

什么是泛型?

通过参数化类型(把类型当作参数传递,编译之前并不能确定具体的操作类型),使一段代码可以操作多种数据类型。

我们肯定希望一个集合能够装不同类型的数据。比如String,Integer…… 虽然我们可以使用Object 来进行上溯造型
 但是我们下溯造型的时候并不能确定具体的类型,很难保证下溯造型的安全进行.
 这时泛型可以让集合不指定具体的使用类型(参数化类型),例如用<E>来代替具体的类型

使用泛型

泛型类

class collection<E> {}

泛型方法

  public E getAndSet(E e,int index){
     objs[index] = e;
     return (E)Objs[index];
 }

泛型子类

 class diyCollection<E> extends MyCollection<E> {}

类型通配符

    //通配符 下限 调用该方法时参数类型只能是Number及其子类
    public static void testGeneric(List<? extends Number > list){
    }
    //通配符 上限 参数类型只能是Number及其父类
    public static void testGeneric1(List<? super Number > list){
    }

完整代码

/**
 * 泛型类.
 * Object数组 存放指定类型的元素
 */
class MyCollection<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];
    }
}

//泛型子类
class diyCollection<E> extends MyCollection<E> {
    @Override
    public E get(int index) {
        return super.get(index);
    }
}


    @Test
    public void testCollection(){
        MyCollection<String> stringMyCollection = new MyCollection<>();
        stringMyCollection.set("abc",0);
        System.out.println(stringMyCollection.get(0));

        MyCollection<Integer> integerMyCollection = new MyCollection<>();
        integerMyCollection.set(66,0);
        System.out.println(integerMyCollection.get(0));
    }

    //通配符 下限 参数类型只能是Number及其子类
    public static void testGeneric(List<? extends Number > list){
    }
    //通配符 上限 参数类型只能是Number及其父类
    public static void testGeneric1(List<? super Number > list){
    }
原文地址:https://www.cnblogs.com/HappyKnockOnCode/p/15598337.html