1

我是 Java 新手,并试图使用Collections.shuffle()来打乱我的 ArrayList 的元素。有人可以帮忙吗?

public class tracklist {

    ArrayList<File> tracklist = new ArrayList<File>();
    String trackListName;

    public static void shuffle(List<?> tracklist, Random rnd) {
        tracklist.shuffle();
    }
}

public class TestDrive {
    public void main(String[] args) {
        //test basic MP3 player
        Mp3Player mp = new Mp3Player();
        File myMusicFile = new File("u:\\02.wav");
        mp.play(myMusicFile);

        //test advanced MP3 player
        Mp3Advance adv = new Mp3Advance();

        //Populate your favs play list or change its name
        tracklist favs = new tracklist();
        favs.addSong(new File("u:\\02.wav"));
        favs.addSong(new File("u:\\03.wav"));

        adv.playTracklist(favs);
        System.out.println("Now Playing:" + favs + "playlist");

        //shuffle play list
        Collections.shuffle(favs);
        System.out.println("Now playing" + favs + "playlist in shuffle");
    }
}

我已经上传了我的试驾和曲目列表代码来提供帮助。我认为我只是试图洗牌错误的对象。

任何帮助将不胜感激。

4

2 回答 2

4

在您的trackList课程中,您将需要更改shuffle方法

public static void shuffle(List<?> tracklist,Random rnd){
    tracklist.shuffle();
}

到(类似)

public static void shuffle(List<?> tracklist,Random rnd){
    Collections.shuffle(tracklist, rnd);
}

现在,就个人而言,我不会费心使方法静态和简单提供一种shuffle打乱内部列表的方法......

public void shuffle(){
    Collections.shuffle(tracklist);
}

所以你可以做一些更像...

tracklist favs = new tracklist();
// Add tracks, do other stuff...
favs.shuffle();

ps-我还建议您熟悉Java 编程语言的代码约定;)

更新

我建议你的TrackList课看起来更像......

public class TrackList {

    private ArrayList<File> tracklist = new ArrayList<File>();
    private String trackListName;

    public void addSong(File file) {
        tracklist.add(file);
    }

    public void removeSong(File file) {
        tracklist.remove(file);
    }

    public void shuffle() {
        Collections.shuffle(tracklist);
    }

    // Additional functionality as required...
}
于 2013-06-28T05:01:51.340 回答
0

如果你想保持面向对象:

public class TrackList extends ArrayList<File>
{
    public void addSong(File track)
    {
        add(track);
    }

    public void shuffle()
    {
        Collections.shuffle(this);
    }
}

接着

TrackList tracks = new TrackList();
tracks.addSong(new File("mp3_01.mp3"));
tracks.addSong(new File("mp3_2.mp3"));
tracks.shuffle();
于 2013-06-28T05:04:51.410 回答