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]