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){ Listsongs = new ArrayList (); 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 c){ for(Song song:c){ System.out.println(song); } }}class SongNameCompare implements Comparator { @Override public int compare(Song o1, Song o2) { // TODO Auto-generated method stub return o1.getName().compareTo(o2.getName()); }}class SongSongerCompare implements Comparator { @Override public int compare(Song o1, Song o2) { // TODO Auto-generated method stub return o1.getSonger().compareTo(o2.getSonger()); }}class SongSongIdCompare implements Comparator { @Override public int compare(Song o1, Song o2) { // TODO Auto-generated method stub return o1.id>o2.id?1:(o1.id { 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