How to ensure that collections in Java contain only one type?

I want to make sure that the collection can only hold one type

It can be said that there is such a method

public Collection<Students> getStudents();

You can write the following code

Collection students = getStudents();
students.add(new Book());

This book does not extend to students Now the collection student contains an incorrect object How can I ensure that this line collection students = getstudents(); impossible?

Solution

If you use collections every time you instantiate a collection Checkedcollection(), it can be enforced at run time There is no denying that it will be a little painful

The above is collected by programming house for you. How to ensure that collections in Java contain only one type? I hope this article can help you solve how to ensure that collections in Java contain only one type? Program development problems encountered.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>