简体   繁体   English

如何确保java中的Collections只包含一个Type?

[英]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:rawtypesjavac警告使用原始类型,并且在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.

相关问题 如何确保在 Java 中只选择了一个 JRadioButton? - How Do I Make Sure Only One JRadioButton Is Selected In Java? 如何确保仅按下一个键 - How to make sure only one key is pressed 对于 Java,如果我想做一个 if 语句以确保输入只包含一个字符,我应该如何进行? - For Java, if I want to do an if statement to make sure the input only takes in one character, how should I proceed? 如何确保只使用covariantly类型参数? - How to make sure a type parameter is used only covariantly? 如何确保集合仅包含接口的每个实现之一 - How to make sure a collection only contains one of each of the implementations of an interface 如何确保仅启动一个线程 - How do I make sure only one thread gets started 如何确保一次只调用一个servlet(不是实例)? - how to I make sure that only one servlet(not instance) is call at a time? 如何确保数据库事务只发生一次? - How to make sure that DB transaction happens only one time? 如何确保Clojure变量是正确的Java类型 - How to make sure a clojure variable is of the right Java type 如何确保只有一个 Java 应用程序实例正在运行? - How to make sure that only a single instance of a Java application is running?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM