我有两个名为Cards
和ActionCard
的类,分别实现ICards
和ICard
,它们包含在两个不同的模块中 - 模块A
包含Cards
和ActionCard
类,并依赖于模块B
,其中包含ICards
和ICard
接口。
我试图在模块Cards
中迭代包含List
的ActionCard
的A
类,并在模块ICards
中迭代B
接口。
我试图用Cards
方法将Iterable<ActionCard>
类定义为Iterator<ActionCard> iterator()
,但由于ActionCard
模块中不知道B
,我想将ICards
定义为Iterable<ICard>
,这意味着iterator()
中的方法Cards
无法返回Iterator<ActionCard>
,因为它是一个完全不同的类型来自Iterator<ICard>
(我不想在模块ICard
中更改为A
,因为我需要使用ActionCard
)。
我尝试使用通配符在Iterable<? extends ICard>
类中定义Cards
,它给出了一个错误:
没有预期的通配符
当我尝试在该类中定义方法Iterator<? extends ICard> iterator(
时,它会给出一个错误:
卡片中的iterator()与java.lang.iterable中的iterator()冲突;尝试使用不兼容的返回类型。
//Module A:
public class Cards implements ICards, Iterable<? extends ICard> {
private List<ActionCard> m_Cards = new ArrayList<>();
@Override
public Iterator<? extends ICard> iterator(){
return m_Cards.iterator();
}
}
public class ActionCard implements ICard {
//...some methods
}
//Module B:
public interface ICards extends Iterable<? extends ICard> {
//...some methods
}
public interface ICard {
//...some methods
}
有没有办法实现我的目标?
怎么样:
public interface ICards<T> extends Iterable<T> {
// ..some methods
}
和
public class Cards implements ICards<ActionCard> {
private List<ActionCard> m_Cards = new ArrayList<>();
@Override
public Iterator<ActionCard> iterator()
{
return m_Cards.iterator();
}
}
因为你的Cards
类总是创建List
的ActionCard
并迭代List
,所以定义它来实现ICards<ActionCard>
是有意义的。
由于Cards
实现ICards
,扩展Iterable
,你不必明确声明Cards
实现Iterable
。