Java的ArrayList的?扩展接口 [英] Java ArrayList of ? extends Interface
问题描述
我有一组类,都实现有法的isValid()
验证接口。我想提出一组对象 - 不同阶层 - 到一个ArrayList,循环通过他们,并呼吁的isValid()
每个
I have a group of classes that all implement a validation interface which has the method isValid()
. I want to put a group of objects--all of different classes--into an ArrayList, loop through them and call isValid()
on each.
下面是我的code
Email email = new email();
Address address = new Address();
ArrayList<? extends Validation> myValidationObjects = new ArrayList();
但是,当我尝试这样做:
But when I try to do:
myValidationObjects.add(email);
我得到:
Add方法在ArrayList类型(捕获#2的?扩展验证)
不适用于参数(电子邮件)
The method add(capture#2-of ? extends Validation) in the type ArrayList is not applicable for the arguments (Email)
两者电子邮件
和地址
实施验证。
根据这个文件,我应该能使用扩展
两种接口和子类。
According to this document, I should be able to use extends
for both interfaces and subclasses.
推荐答案
您可以使用:
List<Validation> myValidationObjects = new ArrayList<>(); // Java 7
List<Validation> myValidationObjects = new ArrayList<Validation>(); // pre Java 7
现在您可以在类实现验证
的任何实例添加到列表中。
Now you can add any instance of a class that implements Validation
to that list.
这篇关于Java的ArrayList的?扩展接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!