首页 > 解决方案 > 实现 Iterator 的抽象类的实例不会迭代

问题描述

似乎当我有一个实现接口的抽象类时,扩展我的抽象类的主类没有拾取接口:

当我使用这个时:

public abstract class MusicIntCollection implements Iterator<Integer>{...}

我无法遍历 StepIndexCollection 的实例:

public class StepIndexCollection extends MusicIntCollection{...}

但是,当我创建这个时:

public class StepIndexCollection extends MusicIntCollection implements Iterator<Integer>{...}

...我可以遍历 StepIndexCollection 的一个实例。

这是我迭代的方式:

this.notes = new StepIndexCollection();
    for (int i : o.notes()) {
        this.notes.add(i);
    }

有没有办法让它从抽象类工作,所以我所有扩展 MusicIntCOllection 的特定类类型也不必实现接口?

标签: javaforeachinterfaceabstract-classiterable

解决方案


您正在实现Iterator接口,而不是Iterable接口。如果你让你的类实现一个Iterable,你将能够使用增强的for循环语法。


推荐阅读