且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中泛型声明的差异

更新时间:2023-01-14 21:06:42

List<String> v = new ArrayList();

这一功能实际上并没有什么不同.右侧的type参数实际上并没有执行任何操作.使用它只是出于风格考虑,并避免使用Raw类型,Raw类型被认为是编程错误.实际上,在Java 7中已经对其进行了增强,因此您可以执行以下操作:List<String> v = new ArrayList<>();,而不必在右侧重复自己.

This one isn't really functionally different. The type parameter on the right side doesn't really do anything. It's used as a matter of style and to avoid the use of a Raw type, which is considered a programming error. In fact, in Java 7 it has been enhanced so you can just do this: List<String> v = new ArrayList<>(); and not have to repeat yourself on the right hand side.

List v = new ArrayList<String>();

没有类型参数的列表称为原始类型.在使用泛型的新代码中声明原始类型通常被认为是编程错误.基本上,当您以这种方式声明时,根本不会进行类型检查,您可以在该列表中放入任何内容.

The list with no type parameter is called a Raw Type. It is generally considered a programming error to declare a Raw Type in new code that is using generics. Basically there is no type checking going on at all when you declare it this way, you can put anything in that list.

Java泛型是编译时检查.因此,重要的是在编译时引用的类型.如果您的引用的类型为Raw List,则在右侧声明的内容无关紧要,这就是编译器将检查的内容.

Java generics are a compile time check. So it is the type of the reference at compile time that matters. If your reference is of type Raw List it doesn't matter what you declared on the right hand side, that is what the compiler will check against.

List<String>并不是真正的具有字符串的列表".这是一个清单,我已要求编译器返回错误和/或警告我是否在其中放置了不是String的内容.如果您忽略了编译器警告,则完全有可能在其中获得不存在的内容." t字符串.

List<String> isn't really a "List that has Strings." It is a "List that I have asked the compiler to return errors and/or warn me if I put something in there that isn't a String. If you ignore compiler warnings, it is perfectly possible to get stuff in there that isn't a String.