The Java™ Tutorials — Generics :Lower Bounded Wildcards 有下限通配符

来源:互联网 发布:淘宝衣服怎么换货 编辑:程序博客网 时间:2024/05/24 00:59

The Java™ Tutorials — Generics :Lower Bounded Wildcards 有下限通配符

原文地址:https://docs.oracle.com/javase/tutorial/java/generics/lowerBounded.html

关键点

  • 功能:限定了类型的下限,也就它必须为某类型的父类
  • 格式:<? super A>

全文翻译

The Upper Bounded Wildcards section shows that an upper bounded wildcard restricts the unknown type to be a specific type or a subtype of that type and is represented using the extends keyword. In a similar way, a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.

有上限通配符会对未知类型可被赋予的具体类型,或这个具体类型的子类型作出限定。而这些限定都是通过使用extends关键字表达出来。《有上限通配符》一文恰恰展示了这些内容。同理,一个有下限通配符也会对未知类型可被赋予的具体类型,或者这个具体类型的超类作出限制。

A lower bounded wildcard is expressed using the wildcard character (‘?’), following by the super keyword, followed by its lower bound: <? super A>.

一个有下限通配符是通过在super关键字前使用通配符“?”,并在关键字后加入上限来表示的:<? super A>

Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.

注意:你可以指定一个通配符的上限,或者下限,但不能同时指定两者

Say you want to write a method that puts Integer objects into a list. To maximize flexibility, you would like the method to work onList<Integer>List<Number>and List<Object> — anything that can hold Integer values.

如果说你想写一个方法,其功能为向列表中插入Integer对象。为了最大化方法的灵活性,你可能希望让方法在List<Integer>List<Number>List<Object>或者任何可以盛装Integer的类型上工作。

To write the method that works on lists of Integer and the supertypes of Integer, such as Integer, Number, and Object, you would specify List<? super Integer>. The term List<Integer> is more restrictive thanList<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.

为了写一个在Integer或Integer超类(如Integer,Number和Object)列表上工作的方法,你需要指定List <? super Integer>List<Integer>List<? super Integer>要更加严格。因为前者仅仅兼容Integer类型的列表,而后者却兼容任何Integer超类的列表。

The following code adds the numbers 1 through 10 to the end of a list:

下面的代码将数字1到10添加到列表的末端:

public static void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i);
}
}

The Guidelines for Wildcard Use section provides guidance on when to use upper bounded wildcards and when to use lower bounded wildcards.

《通配符使用指南》提供了更多关于何时使用上限通配符和下限通配符的更多信息。

0 0
原创粉丝点击