The Java™ Tutorials — Generics :Wildcards and Subtyping 泛型和子类
2016-01-29 11:35
676 查看
The Java™ Tutorials — Generics :Wildcards and Subtyping 泛型和子类
原文地址:https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
关键点
全文翻译
As described in Generics, Inheritance, and Subtypes, generic classes or interfaces are not related merely because there is a relationship between their types. However, you can use wildcards to create a relationship between generic classes or interfaces.正如在《泛型、继承和子类》中描述的那样,泛型类(接口)间并无关联。仅仅因为它们和它们的类型相关。然而,你可以通过使用通配符在泛型类(接口)间建立联系。
Given the following two regular (non-generic) classes:
下面给出两个常规的非泛型类:
class A { /* ... */ } class B extends A { /* ... */ }
It would be reasonable to write the following code:
写下下面代码是十分合理的:
B b = new B(); A a = b;
This example shows that inheritance of regular classes follows this rule of subtyping: class B is a subtype of class A if B extends A. This rule does not apply to generic types:
下面范例表明了常规类的继承遵循了子类的这条规定:如果类B扩展自类A,那么B就是A的子类。这条规则对泛型并不适用:
List<B> lb = new ArrayList<>(); List<A> la = lb; // compile-time error
Given that Integer is a subtype of Number, what is the relationship between
List<Integer>and
List<Number>?
给定一个Integer,而它是Number的子类。那么
List<Integer>和
List<Number>的关系是啥呢?
Although Integer is a subtype of Number,
List<Integer>is not a subtype of
List<Number>and,
in fact, these two types are not related. The common parent of
List<Number>and
List<Integer>is
List<?>.
虽然Integer为Number的子类,但是
List<Integer>并非为
List<Number>的子类,事实上,两者没关系。两者的共同父类为
List<?>
In order to create a relationship between these classes so that the code can access Number’s methods through
List<Integer>’s
elements, use an upper bounded wildcard:
为了在这两个类中创建一个关系,从而让代码可以通过
List<Integer>里面的元素调用Number里面的方法,你需要使用一个有上限通配符:
List<? extends Integer> intList = new ArrayList<>(); List<? extends Number> numList = intList; // OK. List<? extends Integer> is a subtype of List<? extends Number>
Because Integer is a subtype of Number, and numList is a list of Number objects, a relationship now exists between intList (a list of Integer objects) and numList. The following diagram shows the relationships between several List classes declared with both
upper and lower bounded wildcards.
因为Integer是一个Number的子类型,并且numList是一个Number列表,现在intList(一个Integer列表)和numList间就存在了一种关系。下面的图表说明了几种通过有上下限通配符声明的几个List类间的关系。
The Guidelines for Wildcard Use section has more information about the ramifications of using upper and lower bounded wildcards.
更多关于有上(下)限通配符的衍生问题的信息,请参阅《通配符使用指南》
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树