[Java] 对象排序示例
package test.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class Test02 { 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); printList(songs); } public static void printList(Collection<Song> c){ for(Song song:c){ System.out.println(song); } } } class Song implements Comparable<Song>{ private String name; private String songer; private 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()); } }
------------------------------------------------------------------
Always put yourself in the other's shoes.If you feel that it hurts you,it probably hurts others,too.------------------------------------------------------------------