package test.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test03 { public static void main(String[] args){ List<Song> songs = new ArrayList<Song>(); songs.add(new Song(2,"黄家驹","光辉岁月")); songs.add(new Song(5,"刘德华","忘情水")); songs.add(new Song(44,"张学友","吻别")); songs.add(new Song(32,"刘德华","爱你一万年")); songs.add(new Song(123,"黄家驹","冷雨夜")); songs.add(new Song(133,"小虎队","爱")); //Collections.sort(songs); //Collections.sort(songs,new SongNameCompare()); //Collections.sort(songs,new SongSongerCompare()); Collections.sort(songs,new SongSongIdCompare()); printList(songs); } public static void printList(Collection<Song> c){ for(Song song:c){ System.out.println(song); } } } class SongNameCompare implements Comparator<Song>{ @Override public int compare(Song o1, Song o2) { // TODO Auto-generated method stub return o1.getName().compareTo(o2.getName()); } } class SongSongerCompare implements Comparator<Song>{ @Override public int compare(Song o1, Song o2) { // TODO Auto-generated method stub return o1.getSonger().compareTo(o2.getSonger()); } } class SongSongIdCompare implements Comparator<Song>{ @Override public int compare(Song o1, Song o2) { // TODO Auto-generated method stub return o1.id>o2.id?1:(o1.id<o2.id?-1:0); } } class Song implements Comparable<Song>{ private String name; private String songer; int id; public Song(int id,String songer,String name) { super(); this.id = id; this.name = name; this.songer = songer; } @Override public String toString() { return "Song [name=" + name + ", songer=" + songer + ", id=" + id + "]"; } public Song() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSonger() { return songer; } public void setSonger(String songer) { this.songer = songer; } public int compareTo(Song s){ //使用this.id 和s.id做比较,如果返回值>1,表示顺序排序,返回值是<1的数表示倒序 if(this.id>s.id){ return 1; }else if(this.id<s.id){ return -1; }else { return 0; } //根据歌名排序 //return this.getName().compareTo(s.getName()); //根据歌手名排序 //return this.getSonger().compareTo(s.getSonger()); } }
时间: 2024-10-13 06:21:07