将不同的对象添加到Java

时间:2018-10-29 23:03:37

标签: java list arraylist

如果我有一个班级播放列表,一个班级歌曲和一个班级广告,并且创建了一个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;
    }

2 个答案:

答案 0 :(得分:0)

您只能将#include <stdio.h> int main() { int i = 0; // loop counter int size = 0; // size of array int input[20]; printf("enter text here\n"); while((input[i] = getchar()) != '\n' && i < 19) // input text to the array { /* if(input[i]=='c' && input[i+1]=='a' && input[i+2]=='t') // switching characters { input[i]='d'; input[i+1]='o'; input[i+2]='g'; } */ i++; size++; } input[i] = 0;//ALWAYS null-terminate arrays. if (i >= 2); while (input[i + 2]) { if (input[i] == 'c' && input[i + 1] == 'a' && input[i + 2] == 't') { input[i] = 'd'; input[i + 1] = 'o'; input[i + 2] = 'g'; } } } i=0; // reset for next loop while(i < size) // printing the text out ofthe arry { putchar(input[i]); i++; } printf("\n"); return 0; } 个对象添加到播放列表中。

PlayListStuffSong应该扩展Add

喜欢

PlayListStuff

}

public class PlayListStuff {

}

public class Song extends PlayListStuff {

}

答案 1 :(得分:0)

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());