Collections.sort( )分为两部分,一部分为排序规则,一部分为排序算法 。规则用来判断对象,算法则考虑如何进行排序对于自定义对象,sort()不知道规则,所以无法比较,这种情况下一定要定义排序规则。方式有两种:第一种,java.lang下面的一个接口:Comparable。可以让自定义对象实现一个Comparable接口,这个接口只有一个方法comparableTo(Object o)其规则是当前对象与o对象进行比较,返回一个int值,系统根据此值进行排序。如当前对象>o对象,则返回值>0;如当前对象=o对象,则返回值=0;如当前对象<0;[java] view plaincopyimport java.util.*; class User implements Comparable { private String name; private Integer order; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } public int compareTo(User arg0) { return this.getOrder().compareTo(arg0.getOrder()); } } public class Test{ public static void main(String[] args) { User user1 = new User(); user1.setName("zhangsan"); user1.setOrder(10); User user2 = new User(); user2.setName("lisi"); user2.setOrder(6); User user3 = new User(); user3.setName("wangwu"); user3.setOrder(11); User user4 = new User(); user4.setName("zhaoqi"); user4.setOrder(2); List list = new ArrayList (); list.add(user1); list.add(user2); list.add(user3); list.add(user4); Collections.sort(list); for(User u : list){ System.out.println(u.getName()); } } } 第二种方式,java.util下有一个Comparator(比较器)。它拥有compare( )方法,用来比较两个对象。[java] view plaincopyimport java.util.*; class User { //此处无需实现Comparable接口 private String name; private Integer order; public User(){}; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } } public class Test2{ public static void main(String[] args) { User user1 = new User(); user1.setName("zhangsan"); user1.setOrder(10); User user2 = new User(); user2.setName("lisi"); user2.setOrder(6); User user3 = new User(); user3.setName("wangwu"); user3.setOrder(11); User user4 = new User(); user4.setName("zhaoqi"); user4.setOrder(2); List list = new ArrayList (); list.add(user2); list.add(user1); list.add(user3); list.add(user4); Collections.sort(list,new Comparator (){ public int compare(User arg0, User arg1) { return arg0.getOrder().compareTo(arg1.getOrder()); } }); for(User u : list){ System.out.println(u.getName()); } } } 前者代码结构简单,但是只能根据固定的属性排序,后者灵活,可以临时指定排序项,但是代码不够简洁。多字段比较:[java] view plaincopyCollections.sort(list,new Comparator (){ public int compare(User arg0, User arg1) { // 第一次比较专业 int i = arg0.getOrder().compareTo(arg1.getOrder()); // 如果专业相同则进行第二次比较 if(i==0){ // 第二次比较学制 int j=arg0.getXXX().compareTo(arg1.getXXX()); // 如果学制相同则返回按年龄排序 if(j==0){ return arg0.getCCC().compareTo(arg1.getCCC()); } return j; } return i; } });