[英]How to implement a nested iterator class in Java
我有一個Deck
類,其中包含一個<Card>
類型的ArrayList
。 我正在嘗試在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;
}
}
}
這是我的main
:
public static void main(String[] args) {
Deck newDeck = new Deck();
Iterator<Card> iterator = new DeckIterator();
while (DeckIterator.hasNext()) {
Card card = DeckIterator.next();
}
}
}
我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
。
如錯誤所示:在DeckIterator
類中只有一個構造函數,它需要一個List<Card>
但是您嘗試創建一個不帶任何參數的DeckIterator
// REQUIRE
public DeckIterator(ArrayList<Card> cards) {
this.cards = cards;
this.nextCard = 0;
}
// YOUR TRY
Iterator<Card> iterator = new DeckIterator();
當沒有構造函數定義時,默認情況下默認構造函數(no arg)可用,它有一個,您需要顯式定義默認構造函數(或給List<Card>
作為參數,因為在這里您不能指望沒什么因為您沒有給任何卡片而在循環中)
public DeckIterator() {
this.cards = new ArrayList<>();
this.nextCard = 0;
}
錯誤 :您未使用變量名,應該是
while (iterator.hasNext()) {
Card card = iterator .next();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.