import java.util.Comparator;
import java.util.ArrayList;
public class Demo{
public static void main(String[] args){
User u1 =new User("aaa",12);
User u2 =new User("ddd",10);
User u3 =new User("ccc",20);
User u4 =new User("bbb",10);
ArrayList arrayList = new ArrayList();
arrayList.add(u1);
arrayList.add(u2);
arrayList.add(u3);
arrayList.add(u4);
Object[] users =arrayList.toArray();
System.out.println ("排序前。。。。");
for (int i = 0; i
System.out.println (users[i]);
}
System.out.println ("*******************************");
System.out.println ("排序后。。。。。");
//把排序规则交给sort方法。该方法就回按照你自定义的规则进行排序
java.util.Arrays.sort(users,new MyComparator());
for (int i = 0; i
System.out.println (users[i]);
}
}
}
class User{
String name;
int age ;
public User(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return name+":::"+age;
}
}
class MyComparator implements Comparator{ public int compare(Object obj1, Object obj2 ){ User u1 = (User)obj1; User u2 = (User)obj2; if(u1.age>u2.age){ return 1; }else if(u1.age