ArrayList 实例中的 Java 类型规范

标签 java eclipse generics arraylist

在 Eclipse IDE 中使用 JDK 1.8 时,以下行没有原始类型警告:

1) ArrayList<Double> d1 = new ArrayList<>();

但是有一个编译器警告:

2) ArrayList<Double> d2 = new ArrayList();

从语法上来说,唯一的区别是尖括号“<>”。但在这两种情况下都没有实际指定类型。如果尖括号留空,则类型为 Double推断?

最佳答案

一句话 - 是的。

空尖括号 ( <> ) 允许编译器推断泛型类型。如the 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.

再次引用文档,这与使用原始类型有很大不同:

Note that to take advantage of type inference during generic class instantiation, you must use the diamond.

关于ArrayList 实例中的 Java 类型规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704972/

相关文章:

java - 使用工作线程时返回语句

C++确定类是否可比较

vb.net - 在 VB.NET 中使用 XMLSerializer 序列化泛型集合

java - 棋盘上的 8 个皇后

java - 按下按钮时显示数组中的随机文本

java - Foreach 协助使用类变量?

安卓NDK : using other C++ libraries

java泛型问题-当类型是未知对象类型时创建一个泛型列表

java - WebSphere Liberty Core 抛出 java.io.IOException : Stream is closed

Dvorak 的 Eclipse 键盘快捷键