洗牌元素的数组

时间:2013-06-28 04:54:35

标签: java collections arraylist

我是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");
    }
}

我上传了我的试用版和跟踪列表代码以提供帮助。我认为我只是试图改变错误的对象。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

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

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

to(类似)

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-我还建议您熟悉Code Conventions for the Java Programming Language;)

<强>更新

我建议你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...
}

答案 1 :(得分: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();