java 如何对自定义的对象进行排序

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<users.length; 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<users.length; 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<u2.age){
   return -1;
  }else{
   //利用String自身的排序方法。
   //如果年龄相同就按名字进行排序
   return u1.name.compareTo(u2.name);
  }
  
  
 }
} 



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/caoyinghui1986/archive/2008/03/30/2229937.aspx

 

你可能感兴趣的:(java,.net,Blog)