展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > java泛型实例代码分析

java泛型实例代码分析

先简单来段例子:publicvoidtestGenerics(){Collectionnumbers=newArrayList();numbers.add(1);//okCollectiontmp=numbers;//don'twork,youdon'tknowwhattype'tmp'obviouslycontains//tmp.add(1);Collection,又是很多人(包括我)第一反应肯定是“Object是所有java对象的公共父类,所以Collection可以表

本文目录

    先简单来段例子:

    public void testGenerics() {
           Collection numbers = new ArrayList<>();
           numbers.add(1); // ok

           Collection tmp = numbers;
           // don't work, you don't know what type 'tmp' obviously contains
    //        tmp.add(1);

           Collection tmp2 = numbers;
           // don't work, you don't know what subtype 'tmp2' obviously contains
    //        tmp2.add(1);

           Collection integers = new ArrayList<>();
           tmp = integers;
           tmp2 = integers;

           Collection strings = new ArrayList<>();
           tmp = strings;
    //        tmp2 = strings; // don't work
       }

    这个问题其实有点反人类,估计大部分人(包括我)对这种转换的第一反应肯定是“当然是对的。。”,说下我的理解:

    • Collection:表示这个Collection里包含的都是Number类型的对象,可以是Integer/Long/Float,因为编译器可以判断obj instanceof Number == true;

    • Collection:表示这个Collection是Number类型的“某个子类型”的Collection实例,可以是Collection/Collection,所以调用tmp.add(1)是不行的,因为编译器不知道这个tmp包含的元素到底是Number的哪个子类型,编译器无法判断obj instanceof UnknownType的结果;

    • Collection,这个E类型是“一个”具体的类型,而不能是某个parent的多个子类型。

    说到为什么在不明确类型的情况下不能允许写操作,那是为了运行期的安全,举个例子:

    public void testGenerics2() {
       List integers = new ArrayList<>();

       List comparables = integers;
       
       integers.add("1");
       
       comparables.get(0).intValue(); // fail
    }

    如果comparables允许添加Comparable类型,那么运行期就有可能会抛出一些意料之外的RuntimeException,导致方法不正常结束甚至程序crash。

    现在再来说说Collection与Collection,又是很多人(包括我)第一反应肯定是“Object是所有java对象的公共父类,所以Collection可以表示任意类型的集合”,来看个例子:

    public void testGenerics3() {
           List integers = new ArrayList<>();

           List objects = integers; // don't work
           List objects1 = integers; // ok
       }