(没关系:)这是非法的:HashSet<> f;
罢工>
这是合法的:new HashSet<>();
来自类型推断文档:
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.
但是编译器无法推断第二个示例中的类型参数,那么为什么它会编译?
最佳答案
泛型是一个编译时构造。也就是说,它用于强制给定的变量或方法只能用于特定类型或类型集。在您的情况下,编译器可以“推断”最广泛的类型 - Object
,因为 HashSet
没有被分配或返回,因此这些类型永远不会在编译时使用。在运行时,这些类型毫无意义,因为 type erasure .
关于java - 为什么我可以在不以任何方式指定其类型且无法推断类型的情况下创建通用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328394/