每个声明之间有什么区别以及对每个声明的影响是什么?
List listOne = new LinkedList<Shxx>();
List<Shxx> listTwo = new LinkedList<Shxx>();
List listThree = new LinkedList();
List<Shxx> listFour = new LinkedList();
List listOne = new LinkedList<Shxx>();
List<Shxx> listTwo = new LinkedList<Shxx>();
List listThree = new LinkedList();
List<Shxx> listFour = new LinkedList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
丢弃类型信息,还不如根本不使用泛型。
正确充分使用泛型,提供类型安全。
不使用泛型(即 Java 5 之前的代码),没有类型安全。
将导致编译器警告,但其他方面都可以,因为该列表只能通过类型安全引用使用,并且最初为空。无论如何都不应该这样做,因为如果您忽略有关使用原始类型的编译器警告,您也可能会忽略其他不像这个那样良性的警告。从泛型中获得最大类型安全性的最佳方法是消除所有相关的编译器警告。
Throws away the type information, might as well not use generics at all.
Correct full use of generics, provides type safety.
No use of generics (i.e. pre Java 5 code), no type safety.
Will cause a compiler warning, but otherwise OK because the list can only be used through the typesafe reference and is initially empty. Shouldn't be done anyway because if you ignore compiler warnings concerning the use of raw types, you could also be ignoring others that are not as benign as this one. The best way to get the maximum type safety out of generics is to eliminate all related compiler warnings.
listOne
和listThree
只能在代码中用作对象列表(此外,您的 IDE 可能会显示两者的警告,如listOne
的实例化所暗示的那样)对已检查集合的未经检查的使用,而listThree
的实例化是对应检查集合的原始使用)。对于这两个列表,您将能够添加任何类型的对象(
String
作为原型示例)。listTwo
被声明为Shxx
的经典List
。对于此列表,编译器将只允许您添加
Shxx
类型的项目。listFour
的声明编译,并使列表可用(如listTwo
)作为Shxx
的List
(但我不会不推荐这样的写作)。最后,虽然这些列表在您声明的代码中不能以相同的方式使用,但您必须知道它们在运行时都是等效的(但理论上您在很长一段时间内无法克服这些泛型限制) )。
listOne
andlistThree
will only be usable in code as lists of objects (additionnally, your IDE may show warnings for both, as instanciation oflistOne
implies an unchecked use of a checked collection, while instanciation oflistThree
is a raw use of what should be a checked collection).For both theses lists, you'll be able to add any kind of object (
String
as an archetypal example).listTwo
is declared as a classicalList
ofShxx
.For this list, compiler will only allow you to add items of the
Shxx
type.Declaration of
listFour
compiles, and makes list usable (likelistTwo
) as aList
ofShxx
(but I wouldn't recommand such writing).Finally, although these lists won't be usable in the same fashion in your declared code, you have to know that they'll all be equivalent at Runtime (but you theorically won't be able to overcome those generics limitations before a long time).