[英]How to make sure that Collections in java hold only one Type?
I want to make sure that a Collection can hold only one Type. 我想确保Collection只能容纳一个Type。
Lets say there is such a method. 可以说有这样的方法。
public Collection<Students> getStudents();
One can write following code. 可以写下面的代码。
Collection students = getStudents();
students.add(new Book());
Book
does not extend Student
. Book
不扩展Student
。 Now the Collection students contains a wrong Object. 现在Collection学生包含一个错误的对象。 How can I make sure that this line Collection students = getStudents();
我怎样才能确保这一行Collection students = getStudents();
is not possible? 不可能?
This is called a raw type . 这称为原始类型 。 Raw types were introduced for backward compatibility - so that old code still worked against newer JDKs, basically. 引入了原始类型以实现向后兼容性 - 因此旧代码基本上仍可用于较新的JDK。
You can make javac
warn about the use of raw types using -Xlint:rawtypes
, and in IDEs you may be able to make it an actual error, but it's still fundamentally valid Java. 您可以使用-Xlint:rawtypes
让javac
警告使用原始类型,并且在IDE中您可能会使它成为实际错误,但它仍然是基本上有效的Java。
You can enforce it at runtime if you use Collections.checkedCollection() every time you instantiate a Collection. 如果每次实例化Collection时都使用Collections.checkedCollection(),则可以在运行时强制执行它。 Admittedly it would be a bit painful. 不可否认,这会有点痛苦。 :) :)
Jon Skeet made the right answer. Jon Skeet做出了正确的答案。 You can define your Java Compiler on Properties (Or Project-Properties) to get an error if you use a raw-type. 如果使用raw-type,则可以在Properties(或Project-Properties)上定义Java Compiler以获取错误。
你应该使用这种格式:
Collection<Students> s = students.getStudents();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.