【问题标题】:Add different objects to a list in java在java中将不同的对象添加到列表中
【发布时间】:2019-04-02 22:54:38
【问题描述】:

如果我有一个类 PlayList 一个类歌曲和一个类广告,并且我创建一个 Listplaylist(在另一个名为 Index 的类中)我如何将歌曲添加(或添加)到播放列表?它不允许我这样做。我不允许在其中使用 .add(索引)

public static void PrintPlayList() {
        int songsNumber = songs.size();
        int addsNumber = adds.size();
        for(int i=0; i<songsNumber;i++) {
            playlist.add(songs.get(i));

        } 

在里面声明列表之后

 public static List<PlayListStuff> playlist = new ArrayList<PlayListStuff>();

并在 PlayListStuff 类中添加字段歌曲和添加

public class PlayListStuff {
    private Song song;
    private Add  add;
}
public PlayListStuff(Song song) {
        super();
        this.song = song;

    }
    public PlayListStuff( Add add) {
        super();

        this.add = add;
    }

【问题讨论】:

标签: java list arraylist


【解决方案1】:

您只能将PlayListStuff 对象添加到播放列表中。

SongAdd 应该扩展 PlayListStuff

喜欢

public class PlayListStuff {

}

public class Song extends PlayListStuff {

}

public class Add extends PlayListStuff {

}

【讨论】:

    【解决方案2】:
    public final class PlayList {
    
        private final List<Stuff> stuffs = new ArrayList<>();
    
        public void addStuff(Stuff stuff) {
            stuffs.add(stuff);
        }
    
        public interface Stuff {}
    }
    
    public class Song implements PlayList.Stuff {}
    
    public class Add implements PlayList.Stuff {}
    

    您的客户端代码可能如下所示:

    PlayList playList = new PlayList();
    playList.addStuff(new Song());
    playList.addStuff(new Add());
    

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      相关资源
      最近更新 更多