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