Java中泛型声明的差异 [英] Generics Declaration differences in Java

查看:47
本文介绍了Java中泛型声明的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 List<String> v = new ArrayList<String>();

我了解泛型可以帮助您声明ArrayList()具有String类型的Objects.我的问题是 以下内容与上述内容有何不同?

I understand the generics helps you declare that the ArrayList() has Objects of type String. My question is how is the following one different from the above?

 List<String> v = new ArrayList();

或以下与其他人不同的人

or the one below different from others

List v = new ArrayList<String>();

推荐答案

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.

这篇关于Java中泛型声明的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆