简体   繁体   English

&lt;&gt;和之间有什么区别 <?> 在Java通用类型中?

[英]What is the difference between <> and <?> in Java generic types?

When you create a collection field that takes a generic type you can do that by giving it ? 当您创建一个采用通用类型的收集字段时,您可以通过提供它来实现? as the value or nothing at all what is the difference between those: 作为价值或根本没有价值之间的区别是什么:

eg 例如

List<String> list = new ArrayList<?>();

List<String> list = new ArrayList<>();

List<String> list = new ArrayList<String>();

The first statement is just wrong; 第一个陈述是错误的; you cannot instantiate a parameterized class with an unknown type. 您无法实例化具有未知类型的参数化类。 You are likely confusing it with a similar syntax where the unknown is on a declared type as in this dummy example: 您可能将其与类似的语法混淆,其中未知变量位于声明的类型上,如该虚拟示例中所示:

public static String getClassName(Class<?> clazz) {
   return clazz.getName();
}

In the example above, the use of <?> indicates that any type instantiation may be provided. 在上面的示例中,使用<?>表示可以提供任何类型的实例化。

The last two statements are equivalent; 最后两个语句是等效的; in new ArrayList<>() , the String type parameter is inferred by the compiler from the declared type on the left-hand side, while in the last statement this is given explicitly. new ArrayList<>() ,编译器从左侧的声明类型推断出String类型参数,而在最后一条语句中则明确给出了此类型。 As others have correctly noted, this type inference is only available as of Java 7. Prior to Java 7, you can achieve similar type inference by taking advantage of the way that types are inferred on method invocations; 正如其他人已经正确指出的那样,该类型推断仅在Java 7以后可用。在Java 7之前,您可以利用方法调用时推断类型的方式来实现类似的类型推断。 for example, Guava's Lists.newArrayList() allows one to write "Lists.newArrayList()" on the right-hand side without specifying the type a second time, and pre-JDK7 compilers will properly infer the type from the left-hand side there. 例如,Guava的Lists.newArrayList()允许用户在右侧写“ Lists.newArrayList()”而无需第二次指定类型,并且JDK7之前的编译器将从左侧正确推断类型。那里。

Your second example is a new feature introduces with Java 1.7. 第二个示例是Java 1.7引入的新功能。 The empty generic bracers implicitly take the Generic Type of the left side. 空的通用括号隐式采用左侧的通用类型。 So basicly it is the same as your last example. 因此,从根本上讲,它与您的上一个示例相同。

Additionaly your first example is worng (as the others already stated). 另外,您的第一个示例很破旧(正如其他已经提到的那样)。 Valid would be 有效的是

List<?> list = new ArrayList<String>();
List<String> list = new ArrayList<>(); 

is equivalent to 相当于

List<String> list = new ArrayList<String>(); 

Operator <> is called diamond and was introduced in JDK7 操作者<>被称为diamond和JDK7引入

The first statement in your question is invalid. 您问题中的第一条陈述无效。

第一行是通配符 ,后两行是Java 7引入的短代码,它们是相同的oracle源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM