# JAVA 使用Comparator接口实现自定义排序

1、原则
Comparator接口可以实现自定义排序，实现Comparator接口时，要重写compare方法：
int compare(Object o1, Object o2) 返回一个基本类型的整型

2、示例代码

package com.zte.ums.zenap.pm.task.message;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class UserComparator implements Comparator < User > {

public static void main( String[] args ) {
List < User > users = new ArrayList < User >();
users.add( new User( 10, "a" ) );
users.add( new User( 11, "d" ) );
users.add( new User( 15, "s" ) );
users.add( new User( 6, "x" ) );
users.add( new User( 17, "a" ) );
users.add( new User( 17, "b" ) );
users.add( new User( 17, "c" ) );
users.add( new User( 17, "d" ) );
UserComparator comparator = new UserComparator();

users.sort( comparator );
// 也可以使用：Collections.sort( users, comparator );

for ( User u : users ) {
System.out.println( u );
}
}

@Override
public int compare( User u1, User u2 ) {
if ( u1.equals( u2 ) ) {
return 0;
}
else if ( u1.getAge() < u2.getAge() ) {
return 1;
}
else if ( u1.getAge() == u2.getAge() ) {
int f = u1.getName().compareTo( u2.getName() );
if ( f < 0 ) {
return -1;
}
return 0;
}
else {
return -1;
}
}
}

class User {
private int age;
private String name;

public User() {

}

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

public int getAge() {
return age;
}

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

public String getName() {
return name;
}

public void setName( String name ) {
this.name = name;
}

@Override
public String toString() {
return "User [age=" + age + ", name=" + name + "]";
}

}


User [age=17, name=a]
User [age=17, name=b]
User [age=17, name=c]
User [age=17, name=d]
User [age=15, name=s]
User [age=11, name=d]
User [age=10, name=a]
User [age=6, name=x]