用Collections.sort方法對list排序有兩種方法測試
第一種是list中的對象實現Comparable接口,以下:this
/** * 根據order對User排序 */ public class User implements Comparable<User>{ 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("a"); user1.setOrder(1); User user2 = new User(); user2.setName("b"); user2.setOrder(2); List<User> list = new ArrayList<User>(); //此處add user2再add user1 list.add(user2); list.add(user1); Collections.sort(list); for(User u : list){ System.out.println(u.getName()); } } }
輸出結果以下
a
bcode
第二種方法是根據Collections.sort重載方法來實現,例如:對象
/** * 根據order對User排序 */ public class User { //此處無需實現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; } } 主類中這樣寫便可(HastSet——>List——>sort進行排序): public class Test { public static void main(String[] args) { User user1 = new User(); user1.setName("a"); user1.setPrice(11); User user2 = new User(); user2.setName("b"); user2.setPrice(2); Set<User> Hset = new HashSet<User>(); Hset.add(user2); Hset.add(user1); List<User> list = new ArrayList<User>(); list.addAll(Hset); Collections.sort(list,new Comparator<User>(){ public int compare(User arg0, User arg1) { return arg0.getPrice().compareTo(arg1.getPrice()); } }); for(User u : list){ System.out.println(u.getName()); } }
輸出結果以下:排序
a
b接口
注意:默認爲升序,將。return arg0.getOrder().compareTo(arg1.getOrder()); 改成:
return arg1.getOrder().compareTo(arg0.getOrder());
就成降序的了。get