Java ArrayList 的?扩展接口 [英] Java ArrayList of ? extends Interface

查看:23
本文介绍了Java ArrayList 的?扩展接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组类,它们都实现了一个具有方法 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.

这是我的代码

Email email = new email();
Address address = new Address();

ArrayList<? extends Validation> myValidationObjects = new ArrayList();

但是当我尝试这样做时:

But when I try to do:

myValidationObjects.add(email);

我明白了:

ArrayList 类型中的 add(capture#2-of ? extends Validation) 方法不适用于参数(电子邮件)

The method add(capture#2-of ? extends Validation) in the type ArrayList is not applicable for the arguments (Email)

EmailAddress 都实现了验证.

Both Email and Address implement Validation.

根据本文档,我应该能够对接口和子类使用 extends.

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

现在您可以将实现Validation的类的任何实例添加到该列表中.

Now you can add any instance of a class that implements Validation to that list.

这篇关于Java ArrayList 的?扩展接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆