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发行说明。
The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>. 使用通配符(?)指定无界通配符类型,例如,List<?>。This is called a list of unknown type. 这称为未知类型的列表。There are two scenarios where an unbounded wildcard is a useful approach:有两种情况下,无界通配符是一种有用的方法:
Consider the following method, printList:考虑以下方法,PrimtList:
public static void printList(List<Object> list) { for (Object elem : list) System.out.println(elem + " "); System.out.println(); }
The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>. printList的目标是打印任何类型的列表,但它无法实现该目标—它只打印Object实例的列表;它无法打印List<Integer>、List<String>、List<Double>,等等,因为它们不是List<Object>的子类型。To write a generic printList method, use List<?>:要编写通用的printList方法,请使用List<?>:
public static void printList(List<?> list) { for (Object elem: list) System.out.print(elem + " "); System.out.println(); }
Because for any concrete type A, List<A> is a subtype of List<?>, you can use printList to print a list of any type:因为对于任何具体类型A
,List<A>都是List<?>的子类型,您可以使用printList打印任何类型的列表:
List<Integer> li = Arrays.asList(1, 2, 3); List<String> ls = Arrays.asList("one", "two", "three"); printList(li); printList(ls);
Arrays.asList
方法。It's important to note that List<Object> and List<?> are not the same. 需要注意的是,该List<Object>和List<?>不一样。You can insert an Object, or any subtype of Object, into a List<Object>. 你可以把一个Object或Object的任意子类插入到List<Object>。But you can only insert null into a List<?>. 但是null只能插入到List<?>。The Guidelines for Wildcard Use section has more information on how to determine what kind of wildcard, if any, should be used in a given situation.通配符使用指南部分提供了有关如何确定在给定情况下应使用哪种通配符(如果有)的更多信息。