Java笔记4:泛型

作者:陆金龙    发表时间:2022-09-23 21:22   

关键词:  

本文根据 李刚《疯狂Java讲义》第9章源码整理。

第9章 泛型

9.1.3 Java7 泛型的菱形语法

// Java自动推断出ArrayList的<>里是String

List<String> books = new ArrayList<>();

9.3.2 设定类型通配符的上限

List<? extends Shape> shapes

// 同时在画布上绘制多个形状,使用被限制的泛型通配符

public void drawAll(List<? extends Shape> shapes)

{

    for (Shape s : shapes)

    {

        s.draw(this);

    }

}

List<Circle> circleList = new ArrayList<Circle>();

Canvas c = new Canvas();

// 只用了通配符,没有用泛型。由于List<Circle>并不是List<Shape>的子类型,不符合参数类型要求,不能作为该方法的参数来用

// 所以下面代码引发编译错误

c.drawAll(circleList);

9.3.3 设定类型形参的上限

public class Apple<T extends Number>

{

    public static void main(String[] args)

    {

       Apple<Integer> ai = new Apple<>();

       Apple<Double> ad = new Apple<>();

       Apple<String> as = new Apple<>(); // 异常

    }

}

9.4 泛型方法

// 声明一个泛型方法,该泛型方法中带一个T类型形参,

static <T> void fromArrayToCollection(T[] a, Collection<T> c)

{

    for (T o : a)

    {

        c.add(o);

    }

}

public static void main(String[] args){

    // 下面代码中T代表String类型

    String[] sa = new String[100];

    Collection<String> cs = new ArrayList<>();

    fromArrayToCollection(sa, cs);

 

    // 下面代码中T代表Object类型

    Object[] oa = new Object[10];

    Collection<Object> co = new ArrayList<>();

    fromArrayToCollection(oa, co);

 

    // 下面代码中T代表Number类型

    Integer[] ia = new Integer[100];

    Float[] fa = new Float[100];

    Number[] na = new Number[100];

    Collection<Number> cn = new ArrayList<>();

    fromArrayToCollection(ia, cn);

    fromArrayToCollection(fa, cn);

    fromArrayToCollection(na, cn);

 

    // 下面代码中T代表Object类型

    fromArrayToCollection(na, co);

 

    // 下面代码中T代表String类型,但na是一个Number数组,

    // 因为Number既不是String类型,也不是它的子类,所以出现编译错误

    // fromArrayToCollection(na, cs);

}

 

public class RightTest

{

    // 声明一个泛型方法,该泛型方法中带一个T形参

    static <T> void test(Collection<? extends T> from , Collection<T> to)

    {

        for (T ele : from)

        {

            to.add(ele);

        }

    }

    public static void main(String[] args)

    {

        List<Object> ao = new ArrayList<>();

        List<String> as = new ArrayList<>();

        // 因为使用了泛型,下面代码完全正常

        test(as , ao);

   }

}