[英]How to implement a nested iterator class in Java
I have a class, Deck
, which holds an ArrayList
of type <Card>
. 我有一个
Deck
类,其中包含一个<Card>
类型的ArrayList
。 I'm trying to implement a couple of nested Iterator classes inside Deck
(without the use of ListIterator
- the first being one that simply traverses through the ArrayList<Card>
held by Deck
, in order. However, I'm having trouble getting it to work properly: 我正在尝试在
Deck
实现几个嵌套的Iterator类(不使用ListIterator
-第一个是简单地按顺序遍历Deck
持有的ArrayList<Card>
。但是,我很难获取它正常工作:
private static class DeckIterator implements Iterator<Card> {
private int nextCard;
private final ArrayList<Card> cards;
public DeckIterator(ArrayList<Card> cards) {
this.cards = cards;
this.nextCard = 0;
}
@Override
public boolean hasNext() {
if (nextCard > cards.size() - 1) {
return false;
}
else {
return true;
}
}
@Override
public Card next() {
if (hasNext() == true) {
return cards.get(nextCard + 1);
}
else {
return null;
}
}
}
Here's my main
: 这是我的
main
:
public static void main(String[] args) {
Deck newDeck = new Deck();
Iterator<Card> iterator = new DeckIterator();
while (DeckIterator.hasNext()) {
Card card = DeckIterator.next();
}
}
}
I'm getting constructor DeckIterator in class DeckIterator cannot be applied to given types; required: ArrayList<Card>, found: no arguments
我
constructor DeckIterator in class DeckIterator cannot be applied to given types; required: ArrayList<Card>, found: no arguments
得到constructor DeckIterator in class DeckIterator cannot be applied to given types; required: ArrayList<Card>, found: no arguments
constructor DeckIterator in class DeckIterator cannot be applied to given types; required: ArrayList<Card>, found: no arguments
. constructor DeckIterator in class DeckIterator cannot be applied to given types; required: ArrayList<Card>, found: no arguments
。
As the error says : in the DeckIterator
class there is only one constructor, and it requires a List<Card>
but you try to create a DeckIterator
without any parameter 如错误所示:在
DeckIterator
类中只有一个构造函数,它需要一个List<Card>
但是您尝试创建一个不带任何参数的DeckIterator
// REQUIRE
public DeckIterator(ArrayList<Card> cards) {
this.cards = cards;
this.nextCard = 0;
}
// YOUR TRY
Iterator<Card> iterator = new DeckIterator();
The default constructor (no arg) is available by default when there is no constructor define, it there is one, you need to explicitly define the default one (or give a List<Card>
as parameter, because here you can't expect nothin in your loop as you didn't give any card) 当没有构造函数定义时,默认情况下默认构造函数(no arg)可用,它有一个,您需要显式定义默认构造函数(或给
List<Card>
作为参数,因为在这里您不能指望没什么因为您没有给任何卡片而在循环中)
public DeckIterator() {
this.cards = new ArrayList<>();
this.nextCard = 0;
}
Error : You did not use the variable name, it should be 错误 :您未使用变量名,应该是
while (iterator.hasNext()) {
Card card = iterator .next();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.