我有两个名为 Cards
的类和ActionCard
实现ICards
和ICard
分别包含在两个不同的模块中 - module A
包含Cards
和ActionCard
类并依赖于模块B
,其中包含 ICards
和ICard
接口(interface)。
我正在尝试迭代 Cards
包含 List
的类的ActionCard
在模块 A
,并迭代 ICards
模块中的接口(interface)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
类并给出错误:
No wildcard expected
当我尝试定义方法 Iterator<? extends ICard> iterator(
时)在该类中它给出了一个错误:
iterator() in Cards clashes with iterator() in java.lang.iterable; attempting to use incompatible return type.
//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
.
关于java - 如何将 iterable 与继承结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55846094/