我一直在学习 Java(使用 Java 6),并且我注意到,当创建 Collections
对象(例如 ArrayList
)时,必须声明类型引用类型和对象类型中的参数。仅在引用类型中声明类型参数不是更容易吗?或者在某些情况下类型参数可以不同?
例如,下面的类型参数 (String
) 必须声明两次。
List<String> aList = new ArrayList<String>();
最佳答案
Java 7 还引入了 "diamond" form ,它可以推断类型并让您编写更简洁的代码。
If the type argument list to the class is empty — the diamond form "<>" — the type arguments of the class are inferred. It is legal, though strongly discouraged as a matter of style, to have white space between the "<" and ">" of a diamond.
所以,你可以这样写:
List<String> aList = new ArrayList<>();
有几个例子here.
关于java - 在Java中的Collections对象中声明类型参数两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975812/