2013-06-28 114 views
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"); 
    } 
} 

我已經上傳我的兩個試駕和曲目列表代碼,以幫助。我認爲我只是試圖拖曳錯誤的對象。

任何幫助將不勝感激。

+0

'List'沒有洗牌方法和'trackList'不是有效的'Collection'對象 – MadProgrammer

+0

問題是什麼? 您是否嘗試過多次,因爲您有很多機會在洗牌兩個項目的集合後找到相同的訂單。 您應該添加更多曲目並再次測試。 – clement

回答

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我也建議你熟悉Code Conventions for the Java Programming Language

更新

我'd建議你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... 
} 
+0

// new shuffle tracklis tracklist newfavs = new tracklist(); //在此添加曲目ecta favs.addSong(new File(「u:\\ 04.wav」)); favs.addSong(new File(「u:\\ 05.wav」)); newfavs.shuffle(); adv.playTracklist(newfavs); System.out.println(「正在播放:」+ newfavs +「播放列表」); } } –

+0

嗨,謝謝,不過im仍然有問題 –

+0

+1沒有這麼瘋狂 – Bohemian

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