小弟java入门,headfirst java 看到562页,一直是边打代码边编译变学习,
现在在562这个地方运行不出来书上想要的结果,请各位高手看看给个思路。
import java.util.*;
import java.io.*;
public class Jukebox6 {
ArrayList<Song> songList = new ArrayList<Song>();
public static void main(String[] args){
new Jukebox6().go();
}
public void go(){
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
HashSet<Song> songSet = new HashSet<Song>();
songSet.addAll(songList);
System.out.println(songSet);
}
public void getSongs(){
try{
File file = new File("SongList.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line=reader.readLine()) != null){
addSong(line);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public 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 Comparable<Song>{
String title;
String artist;
String rating;
String bpm;
public boolean equals(Object aSong){
Song s = (Song) aSong;
return getTitle().equals(s.getTitle());
}
//用String中的equal()方法覆盖Object类中的equal()方法。
public int hasCode(){
return title.hashCode();
}
//用String中的hasCode()方法覆盖Object类中的hasCode()方法。
public int compareTo(Song s){
return title.compareTo(s.getTitle());
}
Song(String t, String a, String r, String b){ //Song构造函数。引入四个setter参数。
title = t;
artist = a;
rating = r;
bpm = b;
}
public String getTitle(){
return title;
}
public String getArtist(){
return artist;
}
public String getRating(){
return rating;
}
public String getBpm(){
return bpm;
}
public String toString(){
return title;
}
}
要用的Song.txt为
Pink Moon/Nick Drake/5/80
Somersault/Zero 7/4/84
Shiva Moon/Prem Joshua/6/120
Circles/BT/5/110
Deep channel/Afro Celts/4/120
Passenger/Headmix/4/100
Listen/Tahiti 80/5/90
Listen/Tahiti 80/5/90
Listen/Tahiti 80/5/90
Circles/BT/5/110
按书上所诉,运行的结果应该是
[Pink Moon, Somersault, Shiva Moon, Circles, Deep channel, Passenger, Listen, Listen, Listen, Circles]
[Circles, Circles, Deep channel, Listen, Listen, Listen, Passenger, Pink Moon, Shiva Moon, Somersault]
[Circles, Deep channel, Listen, Passenger, Pink Moon, Shiva Moon, Somersault]
但是我运行出来的结果始终为
[Pink Moon, Somersault, Shiva Moon, Circles, Deep channel, Passenger, Listen, Listen, Listen, Circles]