具体类型作为参数的Java类
将“具体”类型的类声明为generics是否有任何意义?
如果是的话,有什么用?
如果没有,编译器允许的任何具体原因是什么?
代码:
public class SomeClass { //... public static void main (String a[]) { // SomeClass iSome = new SomeClass(); // SomeClass jSome = new SomeClass(); SomeClass kSome = new SomeClass(); // ... } }
运行正常,并在我取消注释声明iSome
和jSome
发出编译器错误。
我正试图将这些东西整合在一起“破译”仿制药。
提前致谢。
这不是你的想法。 您正在创建一个名为Integer
的generics类型参数,它会影响java.lang.Integer
。
在类定义中,您调用Integer
的参数也可以只是T
而不改变意义。
AFIK你可以省略Java 7中的generics,编译器会自动添加它,但无论如何都不会在运行时存储。 因此,您必须在左手定义中定义generics,唯一的例外是使用用作通配符的问号。
// here is the generic missing the compiler cannot guess it: SomeClass<> iSome = new SomeClass<>(); // here does the compiler know that you want a Double SomeClass jSome = new SomeClass<>(); // this will also work SomeClass> kSome = new SomeClass();