gpt4 book ai didi

java - 在 Java 的 Collections 对象中声明类型参数两次

转载 作者:行者123 更新时间:2023-11-30 06:15:20 25 4
gpt4 key购买 nike

我一直在学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com