A< T extends B>的区别是什么?和A <?扩展B>? [英] What is the difference between A<T extends B> and A<? extends B>?
问题描述
我是一名新的java学习者。最近我正在阅读泛型编程,并对此感到困惑......
A< T extends B>和A <?扩展B>
首先,这些是完全不同的结构不同的上下文。
A< T extends B>
是泛型类型声明的一部分,例如
public class A< T extends B> {...}
它声明通用类型 A $ c $使用类型参数
必须是 T
,并在 T
上引入一个绑定,这样 B
的子类型。
A< ;?扩展B>
是一个带通配符的参数化类型,它可以在变量和方法声明等中用作普通类型:
A< ;?扩展B> a = ...;
public void foo(A< ;? extends B> a){...}
变量声明,如 A <?扩展B>一个
表示 a
的类型是 A
,它的某些子类型为 B
。
例如,给出这个声明
列表与LT ;?扩展Number>升;
您可以:
$ b $将
Number
的某些子类型的 List
赋值给 l
:
l = new ArrayList< Integer>();
获取 Number
从那个列表:
Number n = l.get(0);
但是,列表 l
,因为您不知道列表的实际类型参数:
Double d = ...;
.add(d); //不会编译
I am a new java learner. Recently I was reading Generic programming and got my self confused with this...
A<T extends B> and A<? extends B>
First of all, those are completely different constructs used in different contexts.
A<T extends B>
is a part of generic type declaration such as
public class A<T extends B> { ... }
It declares generic type A
with type parameter T
, and introduces a bound on T
, so that T
must be a subtype of B
.
A<? extends B>
is a parameterized type with wildcard, it can be used in variable and method declarations, etc, as a normal type:
A<? extends B> a = ...;
public void foo(A<? extends B> a) { ... }
Variable declaration such as A<? extends B> a
means that type of a
is A
parameterized with some subtype of B
.
For example, given this declaration
List<? extends Number> l;
you can:
Assign a
List
of some subtype ofNumber
tol
:l = new ArrayList<Integer>();
Get an object of type
Number
from that list:Number n = l.get(0);
However, you can't put anything into list l
since you don't know actual type parameter of the list:
Double d = ...;
l.add(d); // Won't compile
这篇关于A< T extends B>的区别是什么?和A <?扩展B>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!