1.是list中的對象實(shí)現(xiàn)Comparable接口:
/**
* 根據(jù)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());
}
}
2.根據(jù)Collections.sort重載方法來實(shí)現(xiàn):
Collections.sort(list,new Comparator<user>(){
public int compare(User arg0, User arg1) {
return arg0.getOrder().compareTo(arg1.getOrder());
}
});
3.使用compareTo的注意事項(xiàng)
這個是提供給Integer绊汹,int則不可以。