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\n", list); // 对list按照中文姓氏排序,暂未实现多音字,如单田芳 应该shantianfang Collections.sort(list, new AscNameComparator()); System.out.printf("Asc(family name) sort, list:%s\n", list); // 通过“比较器(AscAgeComparator)”,对list进行排序 // AscAgeComparator的排序方式是:根据“age”的升序排序 Collections.sort(list, new AscAgeComparator()); System.out.printf("Asc(age) sort, list:%s\n", list); // 通过“比较器(DescAgeComparator)”,对list进行排序 // DescAgeComparator的排序方式是:根据“age”的降序排序 Collections.sort(list, new DescAgeComparator()); System.out.printf("Desc(age) sort, list:%s\n", list); } }
时间: 2024-11-06 09:55:26