java - Arraylists 的显式规范

标签 java list arraylist java-7

自 Java7 以来,数组列表的显式规范是否被认为是一种不好的做法?为什么这个版本不需要它?

List<String> foo = new Arraylist<String>(); // before
List<String> bar = new Arraylist<>(); // from Java7

仅仅是因为在List中定义了吗? 谢谢!

最佳答案

Is the explicit specification of array lists considered as a bad practice since Java7?

这不是“不好的做法”——它只是比它可能的要冗长一点。这两个语句具有完全相同的效果,因此从这个意义上说,较长的版本没有任何缺点。您绝对不需要四处“修复”所有旧代码 - 但无论如何在编辑现有代码或编写新代码时,您都可以选择使用较短的形式。

Why is it unneccessary from this version?

因为 Java 7 引入了“菱形运算符”(实际上根本不是运算符),正是为了避免必须冗余地指定类型参数。来自Oracle documentation关于“通用实例创建的类型推断”:

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

从语言的角度来看,这并不是 Java 7 中唯一的新特性 - 再次参见 the documentation了解详情。

关于java - Arraylists 的显式规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952624/

相关文章:

java - 将文本和图片附加到图像

java - 获取 LIMIT 子句中预期的错误非负整数值

java - 如何在java中使用 session 显示方法的输出

java - 为什么 JUnit 测试异常总是失败?

java - 我将如何使用缓冲读取器将 .txt 文件转换为 ArrayList 以及如何操作该对象?

java - 如何在 Java 中将数组列表从一个类复制到另一个类?

C# 6.0 列表出现语法错误, ' , '

list - Haskell:如何在(zip [0..])中进行折叠/构建融合?

python - 优化双for循环以查找二维数组上特定值的计数

java - 二维 ArrayList 放置