【问题标题】:Instance of abstract class that implements Iterator won't iterate实现 Iterator 的抽象类的实例不会迭代
【发布时间】:2019-04-26 05:44:40
【问题描述】:

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

当我使用这个时:

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 的特定类类型也不必实现接口?

【问题讨论】:

    标签: java foreach interface abstract-class iterable


    【解决方案1】:

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

    【讨论】:

    • 如果在抽象类中完成,它是否适用于任何子类?
    • @RobertHarvey 是的。您不必在每个类中直接实现接口。
    猜你喜欢
    • 2014-08-18
    • 2015-11-28
    • 1970-01-01
    • 2012-02-28
    • 2015-12-16
    • 2016-01-05
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多