自 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/