java中Comparator的用法 排序

Comparator强行对某个对象collection进行整体排序的比较函数,可以将Comparator传递给Collections.sort或Arrays.sort。
接口方法:
/**
   * @return o1小于、等于或大于o2,分别返回负整数、零或正整数。
   */
  int compare(Object o1, Object o2);

案例:
model
public class User {

  private String id;
  private int age;

  public User(String id, int age) {
    this.id = id;
    this.age = age;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

}

测试方法:
import java.util.Arrays;
import java.util.Comparator;

public class UserComparator implements Comparator {

  public int compare(Object o1, Object o2) {
    return ((User) o1).getAge() - ((User) o2).getAge();
  }

  /**
   * 测试方法
   */
  public static void main(String[] args) {
    User[] users = new User[] { new User("a", 30), new User("b", 20) };
    Arrays.sort(users, new UserComparator());
    for (int i = 0; i < users.length; i++) {
      User user = users[i];
      System.out.println(user.getId() + " " + user.getAge());
    }
  }

}

原文地址:http://www.blogjava.net/fastunit/archive/2008/04/08/191533.html

你可能感兴趣的:(java,对象排序,Java排序)