有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对来自同一基类的不同对象进行迭代

我有不同的课程来定义一段音乐的结构元素。层次结构是Song>Section>CompositeMusic>MusicTime,所有这些都继承自一个抽象MusicComponent

MusicTime是最底层,它知道播放哪个Chord以及有多少个胯部,并且包含在CompositeMusic对象的条中Section反过来持有CompositeMusics并允许节奏和时间特征的变化

我需要能够递归地遍历Song中的所有Sections,每个Section中的所有CompositeMusics,并在每个CompositeMusic中播放所有MusicTimes。换句话说,迭代每种类型中的所有子类,除非它是MusicTime,在这种情况下,请玩它

我天真地认为我可以在MusicComponent基类上放置一个抽象的List<MusicComponent> getChildren(),这样我就可以以同样的方式迭代任何后代。但是这是不允许的,因为它不接受List<Section>例如

所以我的问题是,递归迭代同一基类派生的不同对象的正确方法是什么

编辑

根据要求,代码示例:

基类

public abstract class MusicComponent {

    public MusicComponent() {

    }

    public abstract void play();
    public abstract boolean addComponent(MusicComponent component);
    public abstract List<MusicComponent> getChildren();

}

子类示例

public class Song extends MusicComponent {

    String songName;
    List<Section> sections;

    public Song(String songName, List<Section> sections) {

        this.songName = songName;
        this.sections = sections;
    }

这就是我想在Song(以及SectionCompositeMusic上做的事情)

@Override
public List<MusicComponent> getChildren() {
    return sections;
}

但是它抛出了一个编译错误,因为它不能隐式地从List<Section>转换到List<MusicComponent>,即使SectionMusicComponent的后代,这也是我希望能够做到的


共 (2) 个答案

  1. # 1 楼答案

    尝试使用List<? extends MusicComponent>作为返回类型

  2. # 2 楼答案

    Java 1.5支持协变返回类型,因此基本上,如果基类方法被重写,getChildren()方法将能够返回MusicComponent子类的任何列表。您需要做的是在使用instanceof迭代检查之前,确保要迭代的列表变量的类型正确