4

我是Java的新手,我对编码还不是很了解,但也许你可以帮助我解决我的问题。我有一个程序应该按字母顺序列出所有歌曲。我想使用 Collections API。但在我的代码中,我不明白。Eclipse 没有给我一个错误,并且在它运行的模拟器上没有正确排序。也许你可以告诉我,转移到我的代码中我必须做什么,让它运行。很抱歉没有你那么好 ;) ...但我还年轻,我想学习所有关于编码的知识。非常感谢,文岑茨 :)

public class SongsManager {

final String MEDIA_PATH = Environment.getExternalStorageDirectory()
        .getPath() + "/";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";
private String mp4Pattern = ".mp4";
private String MP3Pattern = ".MP3";
private String MP4Pattern = ".MP4";
private String m4aPattern = ".m4a";

// Constructor
public SongsManager() {

}

/**
 * Function to read all mp3 files and store the details in
 * ArrayList
 * */
public ArrayList<HashMap<String, String>> getPlayList() {
    System.out.println(MEDIA_PATH);
    if (MEDIA_PATH != null) {
        File home = new File(MEDIA_PATH);
        File[] listFiles = home.listFiles();
        if (listFiles != null && listFiles.length > 0) {
            for (File file : listFiles) {
                System.out.println(file.getAbsolutePath());
                if (file.isDirectory()) {
                    scanDirectory(file);
                } else {
                    addSongToList(file);
                }
            }
        }

    }
    // return songs list array
    return songsList;



}

private void scanDirectory(File directory) {
    if (directory != null) {
        File[] listFiles = directory.listFiles();
        if (listFiles != null && listFiles.length > 0) {
            for (File file : listFiles) {
                if (file.isDirectory()) {
                    scanDirectory(file);
                } else {
                    addSongToList(file);

                }

            }
        }
    }
}

private void addSongToList(File song) {
    if (song.getName().endsWith(mp3Pattern) || song.getName().endsWith(mp4Pattern) || song.getName().endsWith(MP4Pattern) || song.getName().endsWith(MP3Pattern) || song.getName().endsWith(m4aPattern)) {
        HashMap<String, String> songMap = new HashMap<String, String>();
        songMap.put("songTitle",
                song.getName().substring(0, (song.getName().length() - 4)));
        songMap.put("songPath", song.getPath());

        // Adding each song to SongList
        songsList.add(songMap);
    }
}

public static void main (String[] args) {
    List<String> songsList = new LinkedList <String>();
    System.out.println(songsList);
    Collections.sort(songsList);
    System.out.println(songsList);

}



}
4

1 回答 1

6

正如@Matt 指出的那样,只需使用Collections.sort(songsList)--once 填充列表即可。

这将起作用,因为其中的项目songsListString's 和Stringimplements Comparable

于 2013-11-03T20:18:38.727 回答