package com.example.zxlib;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
public class Jukebox {
ArrayList<Song> songList = new ArrayList<Song>();
// scores.put("good",100);
public static void main(String[] args) {
new Jukebox().go();
HashMap<String, Integer> scores = new HashMap<String, Integer>();
scores.put("good",100);
System.out.println(scores.get("good"));
}
class ArtistCompare implements Comparator<Song> {
@Override
public int compare(Song one, Song two) {
return one.getArtist().compareTo(two.getArtist());
}
}
public void go() {
getSong();
;
// System.out.println(songList);
Collections.sort(songList);//collections not collection
System.out.println("Collections.sort(songList):" + songList);
ArtistCompare artistCompare = new ArtistCompare();
Collections.sort(songList, artistCompare);
System.out.println("the collections sorted:" + songList);
HashSet<Song> songHashSet = new HashSet<Song>();
songHashSet.addAll(songList);
int code = songHashSet.hashCode();
System.out.println("songHashSet:" + songHashSet + "code:" + code);
}
void getSong() {
//IO
try {
File file = new File("C:\\Users\\DoctorXu\\Desktop\\song.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
addSong(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
void addSong(String lineToParse) {//解析TXT
String[] tokens = lineToParse.split("/");
Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
System.out.println(nextSong);
System.out.println(tokens[1]);
}
}
这里主要是尝试了head first 书里的代码,但是运行结果并不对。下图可见,hashset可以出去重复部分
这是上面代码中 song这个类,要实现sort,就需要知道拿什么来排序,有两种实现方式,
1,song 实现comparable这个接口,并且实现compareTo这个方法。
2,编写内部类comparetor,通过sort(object,comprator)来排序,这里都是通过返回titl和artist 都是String来比较的。
package com.example.zxlib;
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());//title is String, Sting本来覆盖过equals
}
public int hashCode(){
return title.hashCode();
}
public int compareTo(Song s){
return title.compareTo(s.getTitle());
}
Song(String title, String artist, String rating, String bpm) {
this.title = title;
this.artist = artist;
this.rating = rating;
this.bpm = bpm;
}
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;
}
}