当前位置:首页 > 文章列表 > 文章 > java教程 > java泛型实例代码分析

java泛型实例代码分析

来源:亿速云 2024-04-09 17:09:37 0浏览 收藏

对于一个文章开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《java泛型实例代码分析》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

先简单来段例子:

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
   }