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
. Now the Collection students contains a wrong Object. How can I make sure that this line Collection students = getStudents();
is not possible?
本书不延伸学生。现在Collection学生包含一个错误的对象。我怎样才能确保这一行Collection students = getStudents();不可能?
4 个解决方案
#1
7
You can enforce it at runtime if you use Collections.checkedCollection() every time you instantiate a Collection. Admittedly it would be a bit painful. :)
如果每次实例化Collection时都使用Collections.checkedCollection(),则可以在运行时强制执行它。不可否认,这会有点痛苦。 :)
#2
13
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。
#3
5
Jon Skeet made the right answer. You can define your Java Compiler on Properties (Or Project-Properties) to get an error if you use a raw-type.
Jon Skeet做出了正确的答案。如果使用原始类型,则可以在属性(或项目属性)上定义Java编译器以获取错误。
#4
0
You shoud use this format :
你应该使用这种格式:
Collection<Students> s = students.getStudents();
#1
7
You can enforce it at runtime if you use Collections.checkedCollection() every time you instantiate a Collection. Admittedly it would be a bit painful. :)
如果每次实例化Collection时都使用Collections.checkedCollection(),则可以在运行时强制执行它。不可否认,这会有点痛苦。 :)
#2
13
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。
#3
5
Jon Skeet made the right answer. You can define your Java Compiler on Properties (Or Project-Properties) to get an error if you use a raw-type.
Jon Skeet做出了正确的答案。如果使用原始类型,则可以在属性(或项目属性)上定义Java编译器以获取错误。
#4
0
You shoud use this format :
你应该使用这种格式:
Collection<Students> s = students.getStudents();