问题描述
- comparable问题求教?
- 先上代码
import java.util.*;
import java.io.*;public class Jukebox3
{
** ArrayList songList = new ArrayList();**public static void main(String[] args) { new Jukebox3().go();}public void go() { getSongs(); System.out.println(songList); **Collections.sort(songList);** System.out.println(songList);}void getSongs() { try { String path=""e:SongList.txt""; File file = new File(path); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null) { addSong(line); } } catch (Exception ex) { ex.printStackTrace(); }}void addSong(String lineToParse) { String[]tokens = lineToParse.split(""/""); Song nextSong=new Song(tokens[0]tokens[1]tokens[2]tokens[3]); songList.add(nextSong);}
}
class Song implements ComparableTo{
String title;
String artist;
String rating;
String bpm;Song(String tString aString rString b){ title=t; artist=a; rating=r; bpm=b;}
** public int compareTo(Song s){
return title.compareTo(s.getTitle());
}**public String getTitle(){ return title;}public String getRating(){ return rating;}public String getArtist(){ return artist;}public String getBpm(){ return bpm;}public String toString(){ return title;}
}
java照着例子做的,但是编译还是报错,提示:sort不适用,comparable不适用的2个错误,我觉得会出问题的几行加粗了。看了网上其他人的comparable 的例子,自己找不出问题所在。
求大神解答。谢谢啦!
解决方案
http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822251.html
你是想比较歌曲的title,然后输出???,sort 比较的类型应该不对,你看看例子
解决方案二:
扫了一眼就被难住了,ComparableTo是嘛?
解决方案三:
Comparable接口分析
时间: 2024-12-22 00:52:29