集合里保存的是對(duì)象,分別按對(duì)象屬性(字符串,整型)的升降排序
public class TestSort {
public static void main(String args[]){ List list=new ArrayList(); User u1=new User("2005-10-12",20); u1.setB(false); list.add(u1); User u2=new User("2010-03-25",10); u2.setB(false); list.add(u2); User u3=new User("2009-06-08",50); u3.setB(false); list.add(u3); Collections.sort(list); for(int i=0;i<list.size();i++){ User us=(User)list.get(i); System.out.println(us); } } } //-------------
public class User implements Comparable<User> {
private String name; private int age; private boolean b; public User() {
super(); } public User(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } //排序 public int compareTo(User o) { // TODO Auto-generated method stub //按字符屬性升降排序 if(b){//升 return name.compareTo(o.name)>0? 1 : name.compareTo(o.name)==0 ? 0 : -1; }else{//降 return name.compareTo(o.name)>0? -1 : name.compareTo(o.name)==0 ? 0 : 1; } //按整型屬性升降排序 //return this.age>o.age? -1 : this.age == o.age ? 0 : 1; }
//打印 public String toString(){ return name+" "+age; } } |
|