代码之家  ›  专栏  ›  技术社区  ›  eddiewastaken

如何在Java中实现嵌套迭代器类

  •  0
  • eddiewastaken  · 技术社区  · 7 年前

    我有课, Deck ,其中包含 ArrayList 的类型 <Card> .我试图在内部实现几个嵌套的迭代器类 甲板 (不使用 ListIterator -第一个是通过 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

    1 回复  |  直到 7 年前
        1
  •  0
  •   azro    7 年前

    正如错误所示:在 DeckIterator 类只有一个构造函数,它需要 List<Card> 但你试图创造一个 Deck迭代器 无任何参数

    // REQUIRE
    public DeckIterator(ArrayList<Card> cards) {
        this.cards = cards;
        this.nextCard = 0;
    }
    
    // YOUR TRY
    Iterator<Card> iterator = new DeckIterator();
    

    默认情况下,如果存在 构造函数定义,如果有一个,则需要显式定义默认值(或 列表(<);卡片(>); 作为参数,因为在这里,您不能期望循环中没有任何内容,因为您没有给出任何卡片)

    public DeckIterator() {
        this.cards = new ArrayList<>();
        this.nextCard = 0;
    }
    

    错误 :您没有使用变量名,它应该是

    while (iterator.hasNext()) {
        Card card = iterator .next();
    }