The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
One of the more confusing aspects when learning to program with generics is determining when to use an upper bounded wildcard and when to use a lower bounded wildcard. 在学习使用泛型编程时,一个更容易混淆的方面是确定何时使用上界通配符以及何时使用下界通配符。This page provides some guidelines to follow when designing your code.本页提供了设计代码时要遵循的一些准则。
For purposes of this discussion, it is helpful to think of variables as providing one of two functions:在本讨论中,将变量视为提供以下两个函数之一是有帮助的:
Of course, some variables are used both for "in" and "out" purposes — this scenario is also addressed in the guidelines.当然,有些变量同时用于“输入”和“输出”目的—指南中也讨论了这种情况。
You can use the "in" and "out" principle when deciding whether to use a wildcard and what type of wildcard is appropriate. 在决定是否使用通配符以及合适的通配符类型时,可以使用“in”和“out”原则。The following list provides the guidelines to follow:以下列表提供了应遵循的准则:
These guidelines do not apply to a method's return type. 这些准则不适用于方法的返回类型。Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards.应该避免使用通配符作为返回类型,因为它迫使程序员使用代码来处理通配符。
A list defined by List<? extends ...> can be informally thought of as read-only, but that is not a strict guarantee. 由List<? extends ...>定义的列表可以非正式地认为是只读的,但这不是严格的保证。Suppose you have the following two classes:假设您有以下两个类:
class NaturalNumber { private int i; public NaturalNumber(int i) { this.i = i; } // ... } class EvenNumber extends NaturalNumber { public EvenNumber(int i) { super(i); } // ... }
Consider the following code:考虑下面的代码:
List<EvenNumber> le = new ArrayList<>(); List<? extends NaturalNumber> ln = le; ln.add(new NaturalNumber(35)); // compile-time error
Because List<EvenNumber> is a subtype of List<? extends NaturalNumber>, you can assign le to ln. 因为List<EvenNumber>是List<? extends NaturalNumber>的子类,所以你可以将le分配给ln。But you cannot use ln to add a natural number to a list of even numbers. 但不能使用ln将自然数添加到偶数列表中。The following operations on the list are possible:可以在列表上执行以下操作:
You can see that the list defined by List<? extends NaturalNumber> is not read-only in the strictest sense of the word, but you might think of it that way because you cannot store a new element or change an existing element in the list.您可以看到由List<? extends NaturalNumber>定义的列表不是严格意义上的只读,但您可能会这样想,因为您无法在列表中存储新元素或更改现有元素。