在Java中,我有一个interface I
,一个class C
和一个class D
,都实现了I
:
interface I
{
//some method signatures
}
class C implements I
{
//implement methods from I
}
class D implements I
{
//implement methods from I
}
现在,我创建一个包含元素的List class C
,以及第二个包含元素的List D
:
List<C> c = new LinkedList<C>();
List<D> d = new LinkedList<D>();
我有一种方法想要应用于所有包含实现元素的列表interface I
:
public void modifyList(List<I> l)
{
//call some method defined in I
}
但是,当我尝试调用该函数时,编译器将引发错误:
public void testModification()
{
modifyList(c);
modifyList(d);
}
==> The method modifyList(List<I>) in the type [...] is not applicable for the arguments (List<C>) / (List<D>)
我可以通过重新定义我的列表使其工作,使其显示为
List<I> c1 = new LinkedList<I>();
但是现在c1
可以同时包含C类和D类的Elements,这是我要避免的事情。如何创建一个List,以便可以精确定义它应该包含哪些类的元素,但仍将其用作函数的参数?
您可以尝试使用
public void modifyList(List<? extends I> l) {
// ...
}
该类型应为通配符,表示任何类型,只要其超类为(...),或者在这种情况下为I类即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句