简体   繁体   中英

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.

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?

This is called a raw type . Raw types were introduced for backward compatibility - so that old code still worked against newer JDKs, basically.

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.

You can enforce it at runtime if you use Collections.checkedCollection() every time you instantiate a Collection. Admittedly it would be a bit painful. :)

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.

在此输入图像描述

你应该使用这种格式:

    Collection<Students> s = students.getStudents();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM