Comparator名前、年齢順
2824 ワード
package com.heli.compare;
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;
/**
* @desc Person 。 Person Comparable , Person
*/
public class Person implements Comparable<Person> {
int age;
String name;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return name + " - " + age;
}
/**
* Person : name age ,
*/
boolean equals(Person person) {
if (this.age == person.age && this.name == person.name)
return true;
return false;
}
/**
* @desc “Comparable<String>” , compareTo<T t> 。
* “person ”
*/
@Override
public int compareTo(Person person) {
return name.compareTo(person.name);
// return this.name - person.name;
}
}
/**
* @desc AscAgeComparator “Person age ”
*/
class AscNameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
String one = p1.getName();
String two = p2.getName();
Collator ca = Collator.getInstance(Locale.CHINA);
int flags = 0;
if (ca.compare(one, two) < 0) {
flags = -1;
} else if (ca.compare(one, two) > 0) {
flags = 1;
} else {
flags = 0;
}
return flags;
}
}
/**
* @desc AscAgeComparator “Person age ”
*/
class AscAgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
/**
* @desc DescAgeComparator “Person age ”
*/
class DescAgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p2.getAge() - p1.getAge();
}
}
package com.heli.compare;
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
// ArrayList( )
ArrayList<Person> list = new ArrayList<Person>();
// ArrayList
list.add(new Person(" ", 20));
list.add(new Person(" ", 30));
list.add(new Person(" ", 10));
list.add(new Person(" ", 40));
// list
System.out.printf("Original sort, list:%s
", list);
// list , , shantianfang
Collections.sort(list, new AscNameComparator());
System.out.printf("Asc(family name) sort, list:%s
", list);
// “ (AscAgeComparator)”, list
// AscAgeComparator : “age”
Collections.sort(list, new AscAgeComparator());
System.out.printf("Asc(age) sort, list:%s
", list);
// “ (DescAgeComparator)”, list
// DescAgeComparator : “age”
Collections.sort(list, new DescAgeComparator());
System.out.printf("Desc(age) sort, list:%s
", list);
}
}