1. SongList.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
2. Song.java
package test;
class Song implements Comparable<Song> {
String title;
String artist;
String rating;
String bpm;
public int compareTo(Song s) {
return title.compareTo(s.getTitle());
}
Song(String t, String a, String r, String b) {
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;
}
// 추가된 메소드
public boolean equals(Object aSong) {
Song s = (Song) aSong;
return getTitle().equals(s.getTitle());
}
public int hashCode() {
return title.hashCode();
}
}
===============================================================================
[ 설 명 ]
HashSet 에서 중복을 확인하는 방법은 hashCode() 와 equals() 으로 확인
[참조] Head First Java 책 p595
===============================================================================
3. Jukebox6
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Jukebox6 {
ArrayList<Song> songList = new ArrayList<Song>();
public static void main(String[] args) {
Jukebox6 jukebox = new Jukebox6();
jukebox.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);
}
void getSongs(){
try{
File file = new File("./SongListMore.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null){
this.addSong(line);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
void addSong(String lineToParase){
String[] tokens = lineToParase.split("/");
Song nextSong = new Song(tokens[0],tokens[1],"","");
songList.add(nextSong);
}
}
'Java' 카테고리의 다른 글
개발환경 구축 (1) - JDK, Eclipse 설치 (0) | 2008.09.17 |
---|---|
Collection Framework (0) | 2008.07.31 |
ArrayList 를 Collection.sort() 을 이용한 정렬방법 (0) | 2008.07.24 |
자바 Tip & Tuning Technic (0) | 2007.08.09 |
JAR 파일 포맷의 힘 (0) | 2007.06.15 |